Reputation: 111
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
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
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