skip to Main Content

I’m new to react and api consume, we are working with services of our own api for a college project, we have this get method in the service being use by one of the page components

export const getProductCostumer = async (costumerid, state) => {
  let data = await api
    .get(`ProductCostumer?costumerid=${costumerid}`)
    .then((result) => result.data);
  state(data);
  return data;
};

When the page loads, it says that the state in the get method is undefined despite being set on the component that is being used

const [data, setData] = useState([]);
  const Params = useParams();

  const showAlert = (id) => {
    swal({
      title: "Delete",
      text: "Are you sure you want to delete this?",
      icon: "warning",
      buttons: ["Cancel", "Confirm"],
    }).then((answer) => {
      if (answer) {
        deleteProductCostumer(id);
        swal({
          title: 'Deleted',
          text: 'Price has been deleted',
          icon: 'success',
        }).then(function () { window.location.reload() });

      }
    });
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await getProductCostumer(Params.costumerid, setData);
        setData(response);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [Params.costumerid]);

Previously the same undefined error happened with the costumerid but it got solved using Params, what could be the case for state being undefined? Apologies for poor grammar

Tried changing the useEffect with the same results trying to get past the state undefined

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await getProductCostumer(Params.costumerid, setData);
        const responseData = response.data;
        console.log(responseData);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [Params.costumerid]);

2

Answers


  1. There are a couple of nonsense things in your first snippet:

    1. that’s a function, which returns the useful data. Then, why pass as argument a callback to set the same data?

    2. you correctly prefixed the api call with await. However, you later use the then. You should choose to use async/await or the callback-style, not together.

    Let’s adjust the code:

    export const getProductCostumer = async (costumerid) => {
      let result = await api
        .get(`ProductCostumer?costumerid=${costumerid}`);
      return result.data;
    };
    

    I leave to you to review the rest of the code.

    Login or Signup to reply.
  2. It’s a bit hard to understand what you’re asking. You’re actually casting setData as a variable state (casting a verb as a noun), and calling it twice.

    Overall, I can’t really tell what you’re asking or what the problem is. I would recommend using Cursor or some other AI-enabled IDE to help you with understanding the code

    It might be worth making sure the entire component function isn’t being re-created. You want react to keep calling the same function, and it uses the order of the hooks to keep all of the data persistent

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search