0

I have a state in my app which is something like following:

const [companyCategories, setCompanyCategories] = useState({ loading: true, categories: null });

I fetch my categories from an API and set my categories like below:

  const fetchCategories = useCallback(() => {
    fetch(***link***)
      .then(res => {
        if (!res.ok) {
          throw new Error('Failed to fetch.');
        }
        return res.json()
      })
      .then(data => {
        setCompanyCategories({
          loading: false, categories: data.map((el, index) => {
            return {
              id: el.id,
              title: el.title,
              selected: false
            }
          })
        })
      })
      .catch(err => {
        console.log(err);
      });

  }, []);

and if I log my companyCategories after that:

Object {
  "categories": Array [
    Object {
      "id": 7,
      "selected": false,
      "title": "Casual",
    },
    Object {
      "id": 8,
      "selected": false,
      "title": "Coffe Table",
    },
    Object {
      "id": 10,
      "selected": false,
      "title": "Dining Table",
    },
    Object {
      "id": 11,
      "selected": false,
      "title": "Workstation",
    },
  ],
  "loading": false,
}

and here's my problem : consider I show this categories as buttons to UI of the app and when user tap on each it changes by the color and I need to alter selected attribute of the category to true which by default all of them are false means that none selected. for this I code like this:

  const onRadioBtnClick = (item) => {
    let updatedState = companyCategories.categories.map((el) => {
      if (el.id == item.id) {
        return {
          ...el,
          loading: true,
          categories: {
            ...el.categories,
            selected: !el.selected
          }
        }
      }
      setCompanyCategories(updatedState)
    });
  };

and this doesn't work, updatedState is showing me undefined. how can I manipulate one property of my nested state?

1 Answer 1

1

You placed setCompanyCategories(updatedState) at wrong line.

It should be

const onRadioBtnClick = (item) => {
  let updatedState = companyCategories.categories.map((el) => {
    if (el.id == item.id) {
      return {
        ...el,
        loading: true,
        categories: {
          ...el.categories,
          selected: !el.selected
        }
      }
    }
  });
  setCompanyCategories(updatedState);
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.