skip to Main Content

I am using React with Axios. I have a json file and trying to get the data passed to my React App.

$url is the url of the Json file and when I run console log I can see that the json data is getting logged, so think I am fetching the data correctly, but it does not seem to be assigning the data to my variables.

My console log shows like below

Array [ {…} ]
​
0: Object { title: "Page Title", body: "<p>Page body</p>", uri: "uri.jpg", … }
​
length: 1

This is my code

const PageDetails = () => {
  const [page, setPage] = useState();
  const [morePages, setMorePages] = useState();

  const fetchPageDetails = () => {

    axios({
     url: $url,
     method: 'get'
     })
    .then((response) => {
      console.log(response.data)
      setPage(response.data);
    })
    .catch((error) => {
      console.log(error);
    });
    
  };

  return (

    <h1>{page[0]?.title}</h1>
    <div>{page[0]?.body}</div>

  );
};

However, I get error page is undefined.

How can I pass the json response? Thanks

2

Answers


  1. I get error page is undefined.

    No initial value is provided, so the default is undefined:

    const [page, setPage] = useState();
    

    You can provide an initial value of an empty array if you like:

    const [page, setPage] = useState([]);
    

    Alternatively, you can modify the optional chaining to support an undefined value in page:

    page?.[0]?.title
    
    Login or Signup to reply.
  2. How do you call the fetch function?

    It seems you need to use useEffect to call it on initial render.

    Also you need to set default state.

    const PageDetails = () => {
      const [page, setPage] = useState([]);
      const [morePages, setMorePages] = useState();
    
      const fetchPageDetails = () => {
    
        axios({
         url: $url,
         method: 'get'
         })
        .then((response) => {
          console.log(response.data)
          setPage(response.data);
        })
        .catch((error) => {
          console.log(error);
        });
        
      };
    
      useEffect(fetchPageDetails, [])
    
      return (
    
        <h1>{page[0]?.title}</h1>
        <div>{page[0]?.body}</div>
    
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search