search filter in ReactJS - javascript

how to use search filter: React?
I tried the below method to use search effect in reactjs but the result is not coming in my case. I think I have made a silly mistake somewhere, it would be great if anybody could figure out what I'm trying to solve is.
API end-point URL: http://localhost:8000/api/v1/post_list?search=test
function PostListSearch() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick(event) {
axios
.get(`http://localhost:8000/api/v1/post_list?search=${userId}`, {
cancelToken: signal.token
})
.then(res => {
const posts = res.data;
setPost(posts);
})
.catch(err => {
console.log(err);
});
}
return (
<React.Fragment>
<div class="theme-layout">
<div class="topbar stick">
<div class="top-area">
<div class="top-search">
<form>
<input
type="text"
name="search"
onChange={handleClick}
placeholder="Search keyword"
/>
<button data-ripple>
<i class="ti-search"></i>
</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
{posts.map(post => (
<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>
))}
</div>
</React.Fragment>
);
}
export default PostListSearch;

function PostListSearch() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick(event) {
event.preventDefault()
axios
.get(`http://localhost:8000/api/v1/post_list?search=${userId}`, {
cancelToken: signal.token
})
.then(res => {
const posts = res.data;
setPost(posts);
})
.catch(err => {
console.log(err);
});
}
return (
<React.Fragment>
<div class="theme-layout">
<div class="topbar stick">
<div class="top-area">
<div class="top-search">
<form>
<input
type="text"
name="search"
onChange={handleChange}
placeholder="Search keyword"
/>
<button data-ripple onClick={handleClick}>
<i class="ti-search"></i>
</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
{posts.map(post => (
<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>
))}
</div>
</React.Fragment>
);
}
export default PostListSearch;
try this out bro :D

I believe you can update your map logic and state initialisation as follows. Just copy paste the code as it is and try with both the approaches I have mentioned.
function PostListSearch() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState(""); // CHANGE HERE
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick(event) {
axios
.get(`http://localhost:8000/api/v1/post_list?search=${userId}`, {
cancelToken: signal.token
})
.then(res => {
const posts = res.data;
setPost(posts);
})
.catch(err => {
console.log(err);
});
}
return (
<React.Fragment>
<div class="theme-layout">
<div class="topbar stick">
<div class="top-area">
<div class="top-search">
<form>
<input
type="text"
name="search"
onChange={handleChange}
placeholder="Search keyword"
/>
<button data-ripple onClick={handleClick}>
<i class="ti-search"></i>
</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
{
posts.map((post) => {<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>})
}
</div>
</React.Fragment>
);
}
export default PostListSearch;
Another solution could be to keep initialistion as it is and try to push value in array. For this I have done changes in handleChange method
function PostListSearch() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
let currUser = userId;
currUser.push(event.target.value)
setUserId(currUser );
}
function handleClick(event) {
axios
.get(`http://localhost:8000/api/v1/post_list?search=${userId}`, {
cancelToken: signal.token
})
.then(res => {
const posts = res.data;
setPost(posts);
})
.catch(err => {
console.log(err);
});
}
return (
<React.Fragment>
<div class="theme-layout">
<div class="topbar stick">
<div class="top-area">
<div class="top-search">
<form>
<input
type="text"
name="search"
onChange={handleChange}
placeholder="Search keyword"
/>
<button data-ripple onClick={handleClick}>
<i class="ti-search"></i>
</button>
</form>
</div>
</div>
</div>
</div>
<div class="row">
{
posts.map((post) => {<ul key={post.id}>
<div class="col-lg-8 col-xl-9">
<img src={post.image} alt="" class="img-fluid" />
<h3>{post.title}</h3>
</div>
</ul>})
}
</div>
</React.Fragment>
);
}
export default PostListSearch;
I believe anyone of the above solution should work.

Related

radio button input controlling in react js

I have a form which has both boolean and string data to be shown in. I was able to control text fields with the help of state, but boolean fields are controlled with the help of enable and disable radio button. Was not able to control the boolean fields as there are many to be done. Is there any way that I can get the inputs for the fields?
import React, { useState } from 'react';
import moment from 'moment';
export const ConfigurationPage = (props) => {
const { t } = useTranslation();
const [configResp, setConfigResp] = useState({});
const [configSet,setConfigSet]=useState(null);
const [checked,isChecked]=useState(false);
React.useEffect(() => {
fetchConfig();
}, []);
React.useEffect(() => {
setInputConfig();
}, [configResp]);
const setInputConfig=()=>{
setConfigSet(configResp);
}
const fetchConfig = async() => {
try {
const resp = await APIEndpoint.get(`customer/app/config`);
if(resp.success){
const {result}=resp;
setConfigResp(result);
}
}
catch (resp) {
console.log(resp.msg)
}
}
const onChange = (e) => {
setConfigSet({[e.target.name]: e.target.value})
}
const getDate=()=>{
return moment().subtract(1, 'days').format('YYYY-MM-DD')+"T18:30:00.000Z"
}
return (
<div className="overlay" role="dialog">
<div className="dialog sm-scrollbar">
<div className="dialog__content">
<h2 className="dialog__title subheading-text-medium fontMedium">{preCompile.title}</h2>
<hr />
<div class="dialog__body_container flexRow justifyContentSpaceBetween flexWrap">
<div class="flexCol justifyContentSpaceEvenly ">
<div class=" dialog__container_item input-container">
<div class="dialog__description">
<label class="req_conf">Account Alias</label>
<input
id={''}
name="accountAlias"
onChange={(e)=>onChange(e)}
value={configSet?configSet.accountAlias:""}
type={'text'}
className='edit-input'
/>
</div>
</div>
</div>
<div class="flexCol justifyContentSpaceEvenly ">
<div class=" dialog__container_item input-container">
<div class="dialog__description">
<label class="req_conf">mSwipe</label>
<>
<div className={`dialog__description__radio`}>
<label>Enable</label>
{configSet.mswipeEnabled?<input id="" type="radio"
name="mswipeEnabled"
value={configSet.mswipeEnabled}
checked={configSet?.mswipeEnabled}
onChange={(e)=>onChange(e)} />:<input id="" type="radio"
name="mswipeEnabled"
value={!configSet.mswipeEnabled}
checked={!configSet?.mswipeEnabled}
onChange={(e)=>onChange(e)} />}
<label>Disable</label>
<input id="" type="radio"
name="mswipeEnabled"
value={configSet?configSet.mswipeEnabled:checked}
checked={configSet?.mswipeEnabled}
onChange={(e)=>onChange(e)} />
</div>
</>
</div>
</div>
</div>
</div>
<div className="dialog__footer flexCol alignItemsCenter">
<button className="done-button" onClick={props.onSubmit}>{props.title === 'Edit Item' ? 'Update' : 'Save'}</button>
</div>
</div>
</div>
);
}
Here I am trying to change values of mswipe fields which is a boolean with enable and disabled. Is there any way to do this?

How Can i send image and text user information in react js

Sign up Form Written in JSX
import './SignUp-Form-CSS.css'
import { Link } from 'react-router-dom';
import { useState, useContext } from 'react';
import AuthContext from '../Context_store/AuthContext/AuthContext';
const SignUp = () => {
const [name, setName] = useState(null);
const [password, setPassword] = useState(null);
const [confirmPassword, setConfirmPassword] = useState(null);
const [image, setImage] = useState(null);
const authCtx = useContext(AuthContext);
const nameChangeHandeler = (event) => {
setName(event.target.value)
}
const passwordChangeHandeler = (event) => {
setPassword(event.target.value)
}
const confirmPasswordChangeHandeler = (event) => {
setConfirmPassword(event.target.value);
}
const imageChangeHandeler = (event) => {
setImage(event.target.files[0]);
console.log(event.target.files[0]);
}
const onSubmitHandeler = (event) => {
event.preventDefault()
// const data = {
// username: name,
// password: password,
// confirmPassword: confirmPassword,
// image: image
// }
const data=new FormData();
data.append("name",name);
data.append("password",password);
data.append("confirmPassword",confirmPassword);
data.append("image",image);
// data.append('username',name);
console.log(data);
authCtx.signup(data)
}
return (
<div class="container">
<div class="row">
<div class="col-lg-10 col-xl-9 mx-auto">
<div class="card flex-row my-5 border-0 shadow rounded-3 overflow-hidden">
<div class="card-img-left d-none d-md-flex">
{/* <!-- Background image for card set in CSS! --> */}
</div>
<div class="card-body p-4 p-sm-5">
<h5 class="card-title text-center mb-5 fw-light fs-5">Register</h5>
<form onSubmit={onSubmitHandeler} encType='multipart/form-data' >
<div class="form-floating mb-3">
<input type="text" class="form-control"
id="floatingInputUsername"
onChange={nameChangeHandeler}
placeholder="myusername" required autofocus />
<label for="floatingInputUsername">Username</label>
</div>
{/* <div class="form-floating mb-3">
<input type="email" class="form-control" id="floatingInputEmail" placeholder="name#example.com" />
<label for="floatingInputEmail">Email address</label>
</div> */}
<hr />
<div class="form-floating mb-3">
<input type="password"
class="form-control"
onChange={passwordChangeHandeler}
id="floatingPassword" placeholder="Password" />
<label for="floatingPassword">Password</label>
</div>
<div class="form-floating mb-3">
<input type="password" class="form-control"
onChange={confirmPasswordChangeHandeler}
id="floatingPasswordConfirm" placeholder="Confirm Password" />
<label for="floatingPasswordConfirm">Confirm Password</label>
</div>
<div>
<label>Select Logo </label>
<input name='image' onChange={imageChangeHandeler} type="file" class="form-control my-4" id="logo" placeholder="Select Logo " />
</div>
<div class="d-grid mb-2">
<button class="btn btn-lg btn-primary btn-login fw-bold text-uppercase" type="submit">Register</button>
</div>
<a class="d-block text-center mt-2 small" >Have an account?<Link class="nav-link" to={'/login'}> Sign In</Link></a>
<hr class="my-4" />
<div class="d-grid mb-2">
<button class="btn btn-lg btn-google btn-login fw-bold text-uppercase" type="submit">
<i class="fab fa-google me-2"></i> Sign up with Google
</button>
</div>
<div class="d-grid">
<button class="btn btn-lg btn-facebook btn-login fw-bold text-uppercase"
// onClick={onSubmitHandeler}
type="submit">
<i class="fab fa-facebook-f me-2"></i> Sign up with Facebook
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
export default SignUp;
CONTEXT API
import React, { useState } from "react";
import AuthContext from "./AuthContext";
const AuthContextProvider = (props) => {
const [token, setToken] = useState(null);
const login = (loginDetails) => {
}
const signUp = (signUpDetails) => {
console.log("Sign Up Called ");
fetch('http://localhost:5000/register',
{
method:'POST',
body:signUpDetails
// body:JSON.stringify(signUpDetails),
// headers:{
// 'Content-Type': 'application/json'
// }
}).then((resp) => {
return resp.json()
}).then((data) => {
console.log(data);
return data;
}).catch((err) => {
console.log(err);
})
}
const logout = () => {
}
const values = {
login: login,
signup: signUp,
logout: logout,
token: {
token: token,
setToken: setToken
},
isLoggedIn: !!token
}
return (
<div>
<AuthContext.Provider value={values}>
{props.children}
</AuthContext.Provider>
</div>
)
}
export default AuthContextProvider;
But When AT Node server End All Other filed Is recieved as Empty Except image Data
OUTPUT OF DATA SAVED IN DATABASE
And If I follow the Approach in Which I use Simple Object as the data instead of form Data(), I and with header ( that are under // ) I do not receive images at the backend and only receive user info
One solution could be to send the image as a string (base64) to the backend to save the image.
try to implement this in your react:
import { useState } from "react";
import "./styles.css";
export default function App() {
const [img, setImg] = useState("Image string will come here");
const handleChangeImg = (e) => {
console.log(e.target.files[0]);
const reader = new FileReader();
reader.readAsDataURL(e.target.files[0]);
reader.onloadend = () => {
setImg(reader.result);
};
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<input onChange={handleChangeImg} type="file" name="image" />
<button onClick={()=>setImg("Image string will come here")}>Reset</button>
<h1>{img}</h1>
</div>
);
}
Check the code iin codesandbox here.
Related resources:
FileReader

React useState - save variables to local storage

I'm new in React and state hooks.I'm trying to make a website about creating booklist and save it to local storage. Also uploading image to cloudinary. My problem is ; when i trying to save cloudinary image url to the localstorage, it saves previous url. I think i have a problem about useState hooks but i couldnt figure it. Below is my code.
LocalStorage.js
import React, { useState, useEffect } from 'react'
import BookList from '../../components/BookList'
import CreateBook from '../../components/CreateBook'
const getLocalStorage = () => {
let list = localStorage.getItem('liste')
if (list) {
return JSON.parse(localStorage.getItem('liste'))
} else {
return []
}
}
const LocalStorage = () => {
//state hooks
const [list, setList] = useState(getLocalStorage)
const [bookName, setBookName] = useState('')
const [writerName, setWriterName] = useState('')
const [pageNumber, setPageNumber] = useState('')
const [info, setInfo] = useState('')
const [image, setImage] = useState('')
const [uploadUrl, setUploadUrl] = useState('')
let id
//Function for submit button
const handleSubmit = async (e) => {
e.preventDefault()
// conditions for fill the blanks
if (!bookName || !writerName || !pageNumber || !image) {
setInfo('Please fill the blanks')
} else {
try {
const data = new FormData()
data.append('file', image)
data.append('upload_preset', 'book-list-project')
data.append('cloud_name', 'book-list')
let response = await fetch(
'https://api.cloudinary.com/v1_1/book-list/image/upload',
{
method: 'POST',
body: data,
}
)
let result = await response.json()
setUploadUrl(result.url)
id = new Date().getTime().toString()
const newBook = {
id: id,
bookName: bookName,
writerName: writerName,
pageNumber: pageNumber,
uploadUrl: uploadUrl,
}
setList([...list, newBook])
setBookName('')
setWriterName('')
setPageNumber('')
setInfo('Book created')
setImage('')
} catch (error) {
console.log(error)
}
}
}
//Function for remove specific book from local storage
const removeSpecificBook = (id) => {
setList(list.filter((book) => book.id !== id))
}
// Function for clear all books from local storage
const removeAllBooks = () => {
setList([])
}
useEffect(() => {
localStorage.setItem('liste', JSON.stringify(list))
}, [list])
return (
<div>
<CreateBook
bookName={bookName}
writerName={writerName}
pageNumber={pageNumber}
handleSubmit={handleSubmit}
info={info}
setBookName={setBookName}
setWriterName={setWriterName}
setPageNumber={setPageNumber}
setImage={setImage}
/>
<BookList
items={list}
removeSpecificBook={removeSpecificBook}
removeAllBooks={removeAllBooks}
/>
</div>
)
}
export default LocalStorage
Booklist.js
import React from 'react'
const BookList = ({ items, removeSpecificBook, removeAllBooks }) => {
return (
<div className='container mx-auto'>
<div className='mt-20 flex flex-wrap items-center justify-center'>
{items.map((item) => {
return (
<div key={item.id} className='p-2 m-2 bg-yellow-100 w-1/4'>
<div className='p-1 m-1 flex justify-center'>
<img
className='object-contain h-52 w-52'
src={item.uploadUrl}
alt='some img'
/>
</div>
<div className='p-1 m-1'>
<h5 className='font-semibold'>Book Name</h5>
<h3>{item.bookName}</h3>
</div>
<div className='p-1 m-1'>
<h5 className='font-semibold'>Writer Name</h5>
<h3>{item.writerName}</h3>
</div>
<div className='p-1 m-1'>
<h5 className='font-semibold'>Total Page</h5>
<h3>{item.pageNumber}</h3>
</div>
<div className='flex justify-end'>
<button
onClick={() => removeSpecificBook(item.id)}
className='px-4 py-2 bg-red-500 rounded-full text-white'
>
Remove
</button>
</div>
</div>
)
})}
</div>
{items.length > 1 && (
<div className='flex justify-center my-5'>
<button
onClick={removeAllBooks}
className='px-8 py-4 bg-red-500 rounded-full text-white'
>
Remove All
</button>
</div>
)}
</div>
)
}
export default BookList
CreateBook.js
import React from 'react'
const CreateBook = ({
bookName,
writerName,
pageNumber,
handleSubmit,
info,
setBookName,
setWriterName,
setPageNumber,
setImage,
}) => {
return (
<div>
<div>
<nav className='bg-blue-500 text-center text-white px-6 py-3'>
Create Book
</nav>
</div>
<div className='bg-red-200 mx-auto w-96 rounded-lg flex justify-center mt-20'>
<form onSubmit={handleSubmit}>
<div>
<div className='p-3 text-center'>
<h6>Enter Book Name</h6>
<input
value={bookName}
onChange={(e) => setBookName(e.target.value)}
className='rounded-md'
type='text'
placeholder='Book Name'
/>
</div>
<div className='p-3 text-center'>
<h6>Enter Writer Name</h6>
<input
value={writerName}
onChange={(e) => setWriterName(e.target.value)}
className='rounded-md'
type='text'
placeholder='Writer Name'
/>
</div>
<div className='p-3 text-center'>
<h6>Enter Total Page Number </h6>
<input
value={pageNumber}
onChange={(e) => setPageNumber(e.target.value)}
className='rounded-md'
type='number'
placeholder='Page Number'
/>
</div>
<div className='p-3 text-center'>
<div>
<h6>Upload Image</h6>
</div>
<div className='p-3'>
<input
type='file'
onChange={(e) => setImage(e.target.files[0])}
/>
</div>
</div>
<div className='flex justify-center p-3'>
<button className='bg-blue-500 py-3 px-6 rounded-full text-white'>
Submit
</button>
</div>
<div className='p-3 text-center text-white'>
<h3>{info}</h3>
</div>
</div>
</form>
</div>
</div>
)
}
export default CreateBook
Also please if you have any suggestions about my code structure, tell me. I dont have any programming history and trying to learn from beginning. I need every suggestions to go further learning programming. Thank you in advance.
setUploadUrl(result.url);
id = new Date().getTime().toString();
const newBook = {
id: id,
bookName: bookName,
writerName: writerName,
pageNumber: pageNumber,
uploadUrl: uploadUrl
};
In here you are updating the uploadUrl to the newBook object. But the value of uploadUrl hold the previous record. Instead of setting from uploadUrl, set it from result.url.

How can I pass a data to another component from a list with React?

I got stuck in a part of my code. Basically I have a list and I would like to show more info when I click on item, I have a modal and I would like to show this details on a modal. I managed to pass some information, however, when I pass the array it displays only the last item in the list and I would like to display exactly the one I clicked.
**MODAL COMPONENT**
const Modal = ({ object, modal, setModal }) => {
if (modal)
return (
<div className="modal">
<div className="modal-body">
<div className="modal-header">
<span className="modal-title">{object.title}</span>
<span className="modal-date">xxxxx</span>
</div>
<div className="modal-content">
<div>
<span className="sinopse-style">Overview</span>
<hr></hr>
<p className="modal-description">xxx</p>
</div>
</div>
<div className="modal-footer">
<div className="tags">
<p className="tag-style">Ação</p>
<p className="tag-style">Aventura</p>
<p className="tag-style">Fantasia</p>
</div>
<div className="match-background">
<span className="match-title">75%</span>
</div>
</div>
<h1 onClick={() => setModal(false)}>Close Modal</h1>
</div>
</div>
);
return null;
};
export default Modal;
**RESULTS COMPONENT**
const Movies = (props) => {
const [data, setData] = React.useState("");
const [modal, setModal] = React.useState(false);
const [currentPage, setCurrentPage] = React.useState(1);
const [dataPerPage, setDataPerPage] = React.useState(5);
React.useEffect(() => {
const fetchData = async () => {
await fetch(API).then((response) =>
response
.json()
.then((json) => setData(json))
.catch((error) => console.log(error))
);
};
fetchData();
}, []);
function openModal() {
!modal ? setModal(true) : setModal(false);
}
// Get data per page
const indexLastData = currentPage * dataPerPage;
const indexFirstData = indexLastData - dataPerPage;
const currentData = data && data.results.slice(indexFirstData, indexLastData);
// console.log("current: " + data && currentData);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
return (
<>
{data &&
currentData.map((object) => (
<div className="movies-container" key={object.id} onClick={openModal}>
<div>
<img
className="movie-billboard"
src={`https://image.tmdb.org/t/p/w185${object.poster_path}`}
/>
</div>
<div className="rightSideMovie">
<div className="header-movie-title">
<span className="movie-title">{object.title}</span>
</div>
<div className="match">
<span className="match-percentual">
{object.vote_average * 10}%
</span>
</div>
<span className="release-date">{object.release_date}</span>
<div className="movie-description">
<span>{object.overview}</span>
</div>
</div>
<Modal modal={modal} object={object} setModal={setModal} />
</div>
))}
<Pagination
dataPerPage={dataPerPage}
totalData={data && data.results.length}
paginate={paginate}
/>
</>
);
};
You could tweak your code a bit to select the movie from the list and only have 1 modal. Right now just the last modal will be there since you are using state outside the map.
**MODAL COMPONENT**
// No need to pass in modal -- just pass in the selectedMovie here because that is what you care about
const Modal = ({ selectedMovie, hideModal }) => {
if (selectedMovie)
return (
<div className="modal">
<div className="modal-body">
<div className="modal-header">
<span className="modal-title">{selectedMovie.title}</span>
<span className="modal-date">xxxxx</span>
</div>
<div className="modal-content">
<div>
<span className="sinopse-style">Overview</span>
<hr></hr>
<p className="modal-description">xxx</p>
</div>
</div>
<div className="modal-footer">
<div className="tags">
<p className="tag-style">Ação</p>
<p className="tag-style">Aventura</p>
<p className="tag-style">Fantasia</p>
</div>
<div className="match-background">
<span className="match-title">75%</span>
</div>
</div>
<h1 onClick={hideModal}>Close Modal</h1>
</div>
</div>
);
return null;
};
export default Modal;
**RESULTS COMPONENT**
const Movies = (props) => {
const [data, setData] = React.useState("");
// Just store the selected movie here
const [selectedMovie, setSelectedMovie] = useState(null);
const [currentPage, setCurrentPage] = React.useState(1);
const [dataPerPage, setDataPerPage] = React.useState(5);
React.useEffect(() => {
const fetchData = async () => {
await fetch(API).then((response) =>
response
.json()
.then((json) => setData(json))
.catch((error) => console.log(error))
);
};
fetchData();
}, []);
// Get data per page
const indexLastData = currentPage * dataPerPage;
const indexFirstData = indexLastData - dataPerPage;
const currentData = data && data.results.slice(indexFirstData, indexLastData);
// console.log("current: " + data && currentData);
const paginate = (pageNumber) => setCurrentPage(pageNumber);
return (
<>
{data &&
currentData.map((object) => (
<div className="movies-container" key={object.id} onClick={() => setSelectedMovie(object)}>
<div>
<img
className="movie-billboard"
src={`https://image.tmdb.org/t/p/w185${object.poster_path}`}
/>
</div>
<div className="rightSideMovie">
<div className="header-movie-title">
<span className="movie-title">{object.title}</span>
</div>
<div className="match">
<span className="match-percentual">
{object.vote_average * 10}%
</span>
</div>
<span className="release-date">{object.release_date}</span>
<div className="movie-description">
<span>{object.overview}</span>
</div>
</div>
</div>
))}
// Hiding the modal is just simply setting the selectedMovie to null
<Modal selectedMovie={selectedMovie} hideModal={() => setSelectedMovie(null)} />
<Pagination
dataPerPage={dataPerPage}
totalData={data && data.results.length}
paginate={paginate}
/>
</>
);
};

how to fetch api filter-data in ReactJS?

i have endpoint of filter data like this much-
localhost:8000/api/p_list?product_category=&color=&size=
whenever user filter the data the output would something look like this,
localhost:8000/api/p_list?product_category=1&color=1&size=2
the output of results comes according filter id as per user request to get. how to fetch the value whenever user request the id as per filter in reactjs?
i am probably new to reactjs. i am trying to solve this problem, it would be great if anybody could help me out what i am trying to do. thank you so much in advance.
my method how i tried to solve,
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick(event) {
axios.get(`http://localhost:8000/api/p_list?product_category=${id}&color=${Id}&size=${Id}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Category <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{product_categoryData.map(product_categoryData => (
<p onClick={useEffect}>{product_categoryData.category_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Color <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_colorData.map(filter_colorData => (
<p onClick={useEffect}>{filter_colorData.color_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Size <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_sizeData.map(filter_sizeData => (
<p onClick={useEffect}>{filter_sizeData.size_title}</p>
))}
</div>
</div>
</div>
</div>
</div>
);
};
export default PostListPageByUser;
try storing the values of category size and color in state and make the api call in a useEffect hook that will run every-time the state of one of these values changes.
in generel:
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [category, setCategory] = useState('');
const [color, setColor] = useState('');
const [size, setSize] = useState('');
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
useEffect(() => { axios.get(`http://localhost:8000/api/p_list?product_category=${category}&color=${color}&size=${size}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
})}, [size,color,category])
and in your form modify mutate the state
import React, {useEffect, useState} from "react";
import axios from 'axios';
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
const [productCategory, setProductCategory] = useState(null);
const [productColor, setProductColor] = useState(null);
const [productSize, setProductSize] = useState(null);
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
function handleClick() {
axios.get(`http://localhost:8000/api/p_list?product_category=${productCategory}&color=${productColor}&size=${productSize}`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
}).catch(err => {
console.log(err);
});
}
useEffect(
() => {
handleClick();
},
[productCategory,productColor,productSize],
);
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Category <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{product_categoryData.map(product_categoryData => (
<p onClick={setProductCategory(product_categoryData.category_title)}>{product_categoryData.category_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Color <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_colorData.map(filter_colorData => (
<p onClick={setProductColor(filter_colorData.color_title)}>{filter_colorData.color_title}</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">Size <i class="right fas fa-caret-down"></i> </div>
<div class="select_option_dropdown">
{filter_sizeData.map(filter_sizeData => (
<p onClick={setProductSize(filter_sizeData.size_title)}>{filter_sizeData.size_title}</p>
))}
</div>
</div>
</div>
</div>
</div>
);
};
Below step should happen :-
Onclick set state
2.state change call API
There are several reasons why your onClick prop is not firing when it's changed.
You are calling useEffect directly in your onClick even though you didn't define it in your code.
You are not using useState to set category, colour or size anywhere in your code to use it to make async calls.
import React, { useEffect, useState } from "react";
import axios from "axios";
function PostListPageByUser() {
const [posts, setPost] = useState([]);
const [userId, setUserId] = useState([]);
const [categoryTitle, setCategoryTitle] = useState("");
const [color, setColor] = useState("");
const [size, setSize] = useState("");
let signal = axios.CancelToken.source();
function handleChange(event) {
setUserId(event.target.value);
}
async function handleClick(event) {
try {
const response = await axios.get(
`http://localhost:8000/api/p_list?product_category=${categoryTitle}&color=${color}&size=${size}`,
{
cancelToken: signal.token,
}
);
setPost(response.data);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
this.handleClick();
}, [categoryTitle, color, size]);
return (
<div>
<div class="product_sidebar">
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Category <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{product_categoryData.map((product_categoryData) => (
<p
onClick={setCategoryTitle(
product_categoryData.category_title
)}
>
{product_categoryData.category_title}
</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Color <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{filter_colorData.map((filter_colorData) => (
<p onClick={setColor(filter_colorData.color_title)}>
{filter_colorData.color_title}
</p>
))}
</div>
</div>
</div>
<div class="single_sedebar">
<div class="select_option">
<div class="select_option_list">
Size <i class="right fas fa-caret-down"></i>{" "}
</div>
<div class="select_option_dropdown">
{filter_sizeData.map((filter_sizeData) => (
<p onClick={setSize(filter_sizeData.size_title)}>
{filter_sizeData.size_title}
</p>
))}
</div>
</div>
</div>
</div>
</div>
);
}
export default PostListPageByUser;

Categories

Resources