1

With the below code I would like to use react-select but when I console.log(testUsers) at first this is blank and then data is finally there, but in the select data is blank. Is there any way to not select blank?

My code:

const { request: getUser, isLoading } = useRequest("");
const [testUsers, setUsers] = useState("");

useEffect(() => {
  getUser({
    path: `${someapi}/user?id=${record?.user_uid}`,
    overwritePath: true,
  }).then((data: any) => {
    setUsers(data[0].fullname);
  });
}, [testUsers]);

console.log(testUsers, "/////////////////");

The output of the console:

/////////
////////
////////
some api returns /////////////
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
denmg
  • 360
  • 3
  • 12

2 Answers2

1

It's to know that React runs the callback of an useEffect after all others normal JavaScript codes such as a console.log() and after the JSX is rendered. And even if that wasn't the case, a network request is asynchronous so you get the data after some delay.

The workaround here is to use a conditional rendering. Something like this as an exmple:

{!testUsers ? <p>Loading...</p> : <div>Render actual content</div> }

But the main error you are making here is to add testUsers in the dependency array. Since you are calling a state setter that's muting it you would get an infinite calls. Do like this instead:

useEffect(() => {
  getUser({
    path: `${someapi}/user?id=${record?.user_uid}`,
    overwritePath: true,
  }).then((data: any) => {
    setUsers(data[0].fullname);
  });
}, []);

Lastly, about why you are getting multiple console.log(), you can check this thread to get a detailed answer.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
0

The reason for this behavior is React Life Cycle. what happened is that in the Mounting phases.

  1. constructor()
  2. getDerivedStateFromProps()
  3. render()
  4. componentDidMount().

because render is triggering first you see that blank select in your DOM.

Read more about it: https://www.w3schools.com/react/react_lifecycle.asp.

Solution:

in your JSX you can check if you have a value in your state then render your JSX.

{testUsers && <h1>Show</h1>}
Alpha
  • 1,413
  • 3
  • 9
  • 23