简体   繁体   中英

unable to render json in react component

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,

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>
)

Fixed it by changing the code a bit; the problem was with the indexing

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM