Search code examples
reactjsreact-hooksuse-effect

api data not changing when url_slug is changing in react hook


I am trying to change the data every time, url_slug is changing but the data is not refreshing. getting the same data.

const [relatedSnippets,setrelatedSnippets] = useState([]);
const [loading,setLoading] = useState(false);

useEffect(async ()=>{
      setLoading(true);
      const snippetData = await getData(url_slug); 
      setrelatedSnippets(snippetData.snippets);
      setLoading(false);
 },[url_slug]);
  
 async function getData(url_slug) {
    var config = {
      headers: {
        accept: '*/*',
        'Content-Type': 'application/json',
        'API_ACCESS_KEY': 'hns2V0Ddbkkn8r1XLq3Kw7ZoiBTR0nmA',
      }
    };
    const data = {
      slug:url_slug,
    }
  
    const url = `http://localhost:8000/api/similarsnippets`;
    
    const snippetData = await axios.post(url,data,config);
    const finalData = snippetData.data;
    return finalData;
  }

Solution

  • The useEffect hook's callback needs to be a synchronous function. Move the async function into the callback and then invoke it.

    useEffect(() => {
      const loadData = async () => {
        setLoading(true);
        const snippetData = await getData(url_slug); 
        setrelatedSnippets(snippetData.snippets);
        setLoading(false);
      };
    
      loadData();
    }, [url_slug]);