Home > OS >  How do I make the API rerender and update the component when the search field is updated in React?
How do I make the API rerender and update the component when the search field is updated in React?

Time:06-28

I have a page in my React Gatsby project where I retrieve data from an API and the page renders the details from the API.

I am trying to add a search feature where the API re-renders when the input search field is updated, but it does not work.

Below is the code:

const [search, setSearch] = useState("")
const [people, setPeople] = useState()
let myHeaders = new Headers();
const getPeople = async () => {
    myHeaders.append("Access-Control-Request-Headers", process.env.GATSBY_PEOPLE_ACCESS_CONTROL);
    myHeaders.append("Authorization", process.env.GATSBY_PEOPLE_BEARER);
    const requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };
    try {   
        let response = await fetch(
            process.env.GATSBY_PEOPLE_API   "&search="   search, requestOptions);
        let result = await response.json();
        setPeople(result)
    } catch (err) { console.error(err); }
};
const searchUpdate = (e) => {
    setSearch(e.target.value)
}

useEffect(() => {
    getPeople()
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

return (
        <Fragment>
            <input placeholder="Search.." onChange={searchUpdate}></input>
            <div className="people">
                {people ? Object.values(people).map(person => {
                    return (
                        <div id={"person-" person.id} key={person.id} >
                            {person.name}
                        </div>
                    )
                }) : "Not available.."}
            </div>
        </Fragment >
    )

How do I make the search feature work?

CodePudding user response:

Add search as a dependency in the useEffect method because when the search state change useEffect is called.

useEffect(() => {
    getPeople()
    // eslint-disable-next-line react-hooks/exhaustive-deps
}, [search])

  • Related