Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda