Search code examples
javascriptreactjsapiaxiosuse-effect

React-Axios => Cannot read properties of undefined (reading 'length')


I am trying to retrieve some data from an API. When I console the data it works fine:

import axios from 'axios';

export default function Model() {
  
    const url = "api.blabla.com/blabla"
    const [model, setModel] = useState()
    useEffect(() => {
      const axiosPosts = async () => {
        const response = await axios(url)
        setModel(response.data)
      };
      axiosPosts();
    }, []);

   console.log(model.slug) //prints the slug!!

    
    return (
      <div>
       {model.slug} : {model.name} // TypeError slug undefined
      </div>
    )  

What can be the problem with this code?


Solution

  • It takes time for the api to respond, so at the start model is assigned the value of the parameter you passed to the useState() hook.

    You passed nothing so during the first react render model is undefined.

    One solution could be to change your template to:

    {model?.slug} : {model?.name}
    

    Or make it conditional

    {model && (
      <>
        {model.slug} : {model.name}
      </>
    )}