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
if (!state) return nullfixes it