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

98
Visualizações
usecontext returns undefined during api calls?

I have the below code and I have an issue with calling API call using usecontext in react. Guide me to fix it.

https://codesandbox.io/s/serene-williamson-bbik6?file=/src/App.js

import ReactDOM from "react-dom";
import "./styles.css";

const JediContext = React.createContext();

function Display() {
  const value = useContext(JediContext);
  return <div>{value.total}, I am your Father.</div>;
}

function App() {
  const [data, setData] = useState(0);
  fetch("https://api.npms.io/v2/search?q=react")
    .then((response) => response.json())
    .then((rawData) => {
      console.log(data);
      setData(rawData);
    });
  return (
    <JediContext.Provider value={data.total}>
      <Display />
    </JediContext.Provider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are a few problems with the posted code:

  1. You are accessing total in the Display component, while passing data.total in the JediContext.Provider. I think you intended to pass just data.
  2. fetch runs with every render so your page with keep re-rendering since you are setData(rawData) after fetch is done. This will cause an infinite loop and crash the application. It is common practice (at this point in time), to use useEffect to fetch data. In the future, suspense1 might be used for this purpose but that's experimental now.
  3. One of the error you were getting was because JediContext didn't have a default value. So value.total produces a null pointer exception. To provide a default value to the context, const JediContext = React.createContext(/*provide default value here*/);
  4. You already have the
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

in your index.js. In App.js, you just need to export App as a default function.

Here's a version of your code that is kinda working in Codesand box: https://codesandbox.io/s/infallible-worker-bcix4?file=/src/App.js

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