Search code examples
reactjsuse-effect

Why my code inside useEffect is not runnig and not fetching the url? what am i missing?


I am trying to show the value fetched from this api where i am getting category from another component. I am attatching my code here.

import React, { useState, useEffect } from 'react'
import Categories from './Categories'

function Joke({ category }) {
    console.log("category selected for joke = " + category);
    const jokeId = category;
    const [joke, setJoke] = useState('');
    const [jokeURL, setJokeURL] = useState('');

    useEffect(() =>{
        console.log('......... = '+category);
        fetch('https://api.chucknorris.io/jokes/random?category={category}')
            .then(res => res.json)
            .then(res => setJoke(res));
    }, []);
    console.log("Joke for "+jokeId+" = "+joke);
    return (
        <div>
            {jokeId == ''
                ? <p style={{ textAlign: 'center' , marginTop:'100px' }}>Please choose a category to begin<p style={{ textAlign: 'center' }}>🙂</p></p>
                : <p style={{ textAlign: 'center' , marginTop:'100px'}}>Selected Category: {jokeId}</p>
            }

        </div>
    )
}

export default Joke

Thanks


Solution

  • You are not using Template Literals in fetch function and one more thing is don't forget to write parenthesis. It is not json it is json().

    useEffect(() =>{
      console.log('......... = '+category);
      fetch(`https://api.chucknorris.io/jokes/random?category=${category}`)
       .then(res => res.json())
       .then(res => setJoke(res));
    }, []);
    

    This one should work.