'Update custom hook's variable after initial call
I created a custom fetch hook called useFetch() and initialled it in my App.js component, to render a list of movies when the web app loads up the page. I am trying to load up a different list of movies based of on the user's search (name of the movie). but don't know if I am to update the data variable or call the useFetch again with a different variable.
....
const [searchString, setSearchString] = useState('morbius');
const [movies, setMovies] = useState([]);
const {data, loading } = useFetch(`api-endpoint.com/apikey/${searchString}`});
movies = data.results;
const handleClick = () => {
//this is where i'd like to update the useFetch based of on the user's search string
//and update the data and loading property
}
I want to make use of the custom hook as i know an easier way to get the job done without it. but it's important I use the useFetch()
Solution 1:[1]
Use UseEffect to wrap your function that fetches the data
import React, { useState,useEffect } from "react";
const App = () =>{
const [searchString, setSearchString] = useState('morbius');
const [movies, setMovies] = useState([]);
//fetches data when the component is first loaded
useEffect(() => {
fetchdata();
}, []);
const fetchdata = () =>{
const {data, loading } = useFetch(`api-endpoint.com/apikey/${searchString}`});
movies = data.results;
}
//this is called when you click the search button
const handleClick = () => {fetchdata}
return <div>
//Input field that enables the user to enter his/her search criteria
<input type="text"
value={searchString}
{/*this is an onchange handler that updates the value of the searchstring when a user types*/}
onChange={e => setSearchString(e.target.value)}/>
<button
onClick={handleClick}
>Search</button>
</div>
}
export default App;
Solution 2:[2]
I was able to find a way around it, based on the fact that at the time I posted the question I didn't have a full understanding on how useEffect works.
useEffect(() => {
//fetch request here
},[url]);
for every the url changes it causes the useEffect to rerun which changes the component the data automatically. In other sense, i structured my code in such a way that the url variable will change when the user clicks the search button or the the enter button.
const [searchText, setSearchText] = useState('');
const [urlText, setUrlText] = useState('superman');
const handleClick = () => {
setUrlText(searchText);
}
....
<input
value={searchText}
onChange=(val)=> setSearchText(val)
></input>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Octagod |