Home > Mobile >  unable to render json in react component
unable to render json in react component

Time:11-10

I'm having a bit of an issue rendering a JSON object in a React component. I want to get the meaning of a random word and then render it in page.

My App.js;

function App() {
const [meaning,setMeaning] = useState([]);
};

useEffect(()=>{
    getMeaning()
}, [])

const getMeaning = async ()=>{
  const response = await fetch(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
 const data = await response.json();
  setMeaning(data) 
}

<AppContext.Provider value={{word,setWord, meaning,setMeaning}}

my Meaning.js

function Meaning(){
    const{
        meaning,
        setMeaning,
    } = useContext(AppContext);

    if (!meaning.length) return <div>loading</div>

    return{meaning}
// tried return json.stringify{meaning} as well //


}

I do receive the object as I can console.log it. How can I render it on page? Where am I going wrong?

Thanks in advance,

CodePudding user response:

You can't render objects in React. You can convert the object to a string and render the string if you like

return (
  <div>{JSON.Stringify(meaning)}</div>
)

CodePudding user response:

Fixed it by changing the code a bit;

function Meaning() {
    const [meaning,setMeaning] = useState([]);
    
    const {
        correctWord
    } = useContext(AppContext)

    useEffect(()=>{
        axios.get(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`)
        .then(res=>{
            console.log(res)
            setMeaning(res.data[0])
            
        })
        .catch(err => {
            console.log(err)
            
        })
        
    },[])
  return (
<div>
        <ul>
                {
                    
                    <div>
                    {meaning.word} {""}
                    <p>{meaning.phonetic}</p>
                    <p>{meaning.meanings[0]?.partOfSpeech}</p>
                    <p>{meaning.meanings[0]?.definitions[0]?.definition}</p>
                    
                    </div>
                    
                }
        </ul> 
    </div>

I set the function in the Meaning.js and then just called the component in the App.js.

Thanks for taking time to try and help.

  • Related