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

130
Visualizações
Get the first value from api request in React JS

In my react js application i use react-select => library. https://react-select.com/home#getting-started

import "./styles.css";
import Select from 'react-select'
import { useState, useEffect } from "react";
export default function App() {
  const [state, setState] = useState();
 
  useEffect(() => {
    const response = fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => setState(json?.map((i) => {
      return {label: i.name, value: i.name}
    })))
  },[])
  console.log(state?.[0])
  return (
    <div className="App">
      <Select
      defaultValue={state?.[0]} //expect the first value that comes from back-end
      options={state} 
      /> 
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

How you can notice i set as initial value the first value that comes from api defaultValue={state?.[0]}, but the value does not appear as default value, even in the console.log it appears. I assume that this happens because of undefined value on the first render, so in the first render state?.[0] is undefined, but after that the value appears in the console. How to get the initial value inside the select?
demo: https://codesandbox.io/s/hopeful-keldysh-6xynq?file=/src/App.js:0-705

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are correct that the useEffect makes the API call after the first render. For most cases, this is a good thing, as it allows you render content, such as a loading spinner, while you are waiting for the API call to finish:

export default function App() {
  const [state, setState] = useState();
 
  useEffect(() => {
    const response = fetch('https://jsonplaceholder.typicode.com/users')
    .then(response => response.json())
    .then(json => setState(json?.map((i) => {
      return {label: i.name, value: i.name}
    })))
  },[])

  if (!state) {
      // you can display a loading spinner here if you want
      return null;
  }

  // Once we've reached this point on subsequent renders, state should be defined
  return (
    <div className="App">
      <Select
      defaultValue={state.[0]} //expect the first value that comes from back-end
      options={state} 
      /> 
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

Also note that because you are using defaultValue, it is essential that you have state defined at the time the Select component is initially rendered/mounted as subsequent changes that you send to defaultValue will not affect the current value (as the value was already "defaulted" to undefined).

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