Home > Net >  My response data is not stored into the variable in react js
My response data is not stored into the variable in react js

Time:06-12

I am trying to store my response data into the activityType variable, inside the useEffect I am looping an API based on tabs value, the API will return is the value true or false, and I am able to get the values on my console but when I try to store the data I am getting empty array.

  const tabs = [
    // {value: 'All', label: `${i18n.t('AllActivity')}`},
    {value: 'ActSendGift', label: `${i18n.t('Gifts')}`},
    {value: 'ActSubscribe', label: `${i18n.t('Subscribers')}`},
    {value: 'ActFollow', label: `${i18n.t('Followers')}`},
  ];

  const activityType: any = [];

  useEffect(() => {
    async function fetchData() {
      return tabs.map(async (item: any) => {
        return await Api.user
          .getSettingValues(item.value)
          .then((response: any) => {
            // console.log(response.settingValue); // true
            // console.log(item.value); "ActSendGift"
            return activityType.push(response.settingValue);
          });
      });
    }
    fetchData();
  }, [activityFeedData.activityList, activityType]);

CodePudding user response:

you can use 'useState' hook instead of declaring a variable in react.

first you need to import the hook

import {useState, useEffect} from 'react'

and inside your functional component you can update the state after fetching the data.

const [activityType, setActivityType] = useState<any>([])

useEffect(() => {
    async function fetchData() {
      return tabs.map(async (item: any) => {
        return await Api.user
          .getSettingValues(item.value)
          .then((response: any) => {
          // console.log(response.settingValue); // true
          // console.log(item.value); "ActSendGift"
          return setActivityType(response.settingValue);
        });
    });
    fetchData();
}, [activityFeedData.activityList, activityType]);

The useState hook returns two values, One is the state variable and the second one is the state update function. The component will re-render automatically as the state changes.

CodePudding user response:

Try putting this array into a state and ensure that the variables that are in the usefct dependency array are being updated so that this block is executed.

const tabs = [
    {value: 'ActSendGift', label: `${i18n.t('Gifts')}`},
    {value: 'ActSubscribe', label: `${i18n.t('Subscribers')}`},
    {value: 'ActFollow', label: `${i18n.t('Followers')}`},
  ];

  const [activeType, setActiveType] = useState([])

  useEffect(() => {
    async function fetchData() {
      return tabs.map(async (item: any) => {
        return await Api.user
          .getSettingValues(item.value)
          .then((response: any) => setActiveType(response.settingValue));
      });
    }
    fetchData();
  }, [activityFeedData.activityList]);

  • Related