Yogesh
Yogesh

Reputation: 111

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

Upvotes: 0

Views: 156

Answers (2)

Sandeep Anumalla
Sandeep Anumalla

Reputation: 38

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.

Upvotes: 2

MB_
MB_

Reputation: 1747

Try :

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

DEMO : Stackblitz

Upvotes: 0

Related Questions