Data comming from api but not set in state

30 views Asked by At

I am trying to set data to state but I am unable to set in state following is the folder hirarachay. -- next js

view/src/app/page/WhyChoseUS.js
'use client';
import React, { useState, useEffect } from 'react';
import WhyChooseUsChild from './WhyChooseUsChild';
import { urlApi } from '../url';

const WhyChooseUs = () => {
  const [whyChooseUsData, setWhyChooseUsData] = useState([]);
  const [blogPosts, setBlogPosts] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response1 = await fetch(`${urlApi}/whychooseus/`);
        const whyChooseUsData = await response1.json();

        const response2 = await fetch(`${urlApi}/blog/`);
        const blogPosts = await response2.json();

        setWhyChooseUsData(whyChooseUsData);
        setBlogPosts(blogPosts);
      } catch (error) {
        console.error('Error fetching data:', error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchData();
  }, []);

  return (
    <>
      {isLoading ? (
        <p>Loading data...</p>
      ) : (
       <WhyChooseUsChild data={whyChooseUsData} data2={blogPosts} />
      )}
    </>
  );
};

export default WhyChooseUs;

trying to save to state and sent to but no data set i am calling this to src/layout.js

1

There are 1 answers

0
ColdCoffee On

I would recommend a few things to help trace down this issue:

  1. Verify you're api is working as expected and hit it directly with Postman or some other networking client while the host is running (on local host or a remote location)

  2. Verify the application is making the request (as defined in your successful postman attempt)

  3. Verify the return value from the fetch call and make sure it has resolved data and it hasn't just returned you a promise or something else unexected.