Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
React context - state not true

Im making a project and got stucked at context file. I want my state planet to be true so i can use it in my component file. At the start it becomes true showing the right index of the array but in the end its becoming undefined. Can someone point me out what is causing "planet" state to be undefined at the end? Im talking about if statement - if (planet) {...}. Im attaching code from context file and screen of my browser console. Would be nice if someone also told me if i can change state in its own setting function e.g. setPlanets(planet[0]).

import React from "react";
import { useState, useEffect } from "react";

export const Context = React.createContext({
  onChooseMoon: () => {},
  onChooseMars: () => {},
});

const ContextProvider = (props) => {
  const [planet, setPlanets] = useState();

  useEffect(() => {
    fetch("./data.json")
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        const transformedData = data.destinations.map((destination) => {
          return {
            name: destination.name,
            img: destination.images.png,
            desc: destination.description,
            dist: destination.distance,
            travel: destination.travel,
          };
        });
        setPlanets(transformedData);
      });
  }, []);

  if (planet) {
    setPlanets(planet[0]);
    console.log(planet[0]);
    console.log("hello");
  }

  const setMoonHandler = () => {
    setPlanets(planet[0]);
  };

  const setMarsHandler = () => {
    setPlanets(planet[1]);
  };

  return (
    <Context.Provider
      value={{
        planet: planet,
        onChooseMoon: setMoonHandler,
        onChooseMars: setMarsHandler,
      }}
    >
      {props.children}
    </Context.Provider>
  );
};

export default ContextProvider;

enter image description here

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here's a breakdown of what's going on:

  1. Component mounts, value of planet is undefined, useEffect is triggered. When useEffect runs setPlanets(transformedData) rerender is triggered.
  2. Value of planet is now whatever transformedData was (I'm assuming an array of planet objects). Since planet is truthy, setPlanets(planet[0]) runs, causing a rerender.
  3. Value of planet is now whatever transformedData[0] was (a single planet). Since planet is still truthy, setPlanets(planet[0]) runs again, causing a rerender.
  4. Value of planet is now whatever transformedData[0][0] was. Since transformedData[0] was not an array and probably doesn't have the key 0, the value of planet is now undefined again.

The issue is that if ever planet becomes defined, running setPlanet(planet[0]) will run until the value of planet becomes undefined again.

I think what you meant to do (judging by the naming) was to have two separate state variables. One to hold all of the planets, and one to hold a single (active/focused) planet.

Here's an example:

const ContextProvider = (props) => {
  const [activePlanet, setActivePlanet] = useState();
  const [planets, setPlanets] = useState([]);

  useEffect(() => {
    fetch("./data.json") // same as before
  }, []);

  useEffect(() => {
    if (!activePlanet && planets.length > 0) {
        setActivePlanet(planets[0]);
        console.log(planets[0]);
        console.log("hello");
    }
  }, [activePlanet, planets]);

  // ...
};

Also it's generally a good idea to wrap all state updating logic in hooks (or tied to events like clicks), so I've added a useEffect to wrap the setActivePlanet call.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!