0

here is my code

import React, { useState } from "react";

function Search(props) {
    const [user, setUser] = useState("tab21");

    const selectUser = (enteredUser) => {
        setUser(enteredUser === "" ? "tab21" : enteredUser);

        props.getuser(user);
        console.log("user in search", user);
    };

    return (
        <div className="bg-black w-full p-2 flex px-4 space-x-3">
            <input
                type="text"
                name="user"
                id="user"
                placeholder="tab21"
                className="p-1 w-4/5 rounded-md"
                required
            />
            <button
                type="submit"
                className="p-1 w-1/5 bg-green-500 rounded-md text-white hover:bg-emerald-500"
                onClick={() =>
                    selectUser(document.getElementById("user").value)
                }
            >
                Search
            </button>
        </div>
    );
}

export default Search;

i do understand that it is not able to render by that time but how to get it to wait till it updates the state.

I tried to find options on the internet and saw many people have this problem but i am not able to collect and apply the same here.

tab21
  • 1
  • 1
  • Does this answer your question? [setState doesn't update the state immediately](https://stackoverflow.com/questions/41278385/setstate-doesnt-update-the-state-immediately) – Ronny Efronny Apr 17 '23 at 08:39
  • Welcome to StakcOverflow. Your question is quite common and is often asked on this site. I suggest you look around at some of the existing answers, and maybe read a guide on React state updates. In short, this is because React does not update the state immediately. You need to either use the function input, or "react" to the state update with `useEffect`. – Ronny Efronny Apr 17 '23 at 08:42
  • Simply put, never use a state right after updating it. Updates takes place only when all other logic is resolved, therefore in your context you want to use the entereduser values which you already know is up to date instead of the state which won't be updated until after that logic happened with the old state. It gives you the impression that you need to double clic but it's not true. – N.K Apr 17 '23 at 09:11
  • Thanks, I think I got it. Now that I see it again I don't think I need to use useState here. – tab21 Apr 17 '23 at 15:51

1 Answers1

0

This code should work for you:

const selectUser = (enteredUser) => {
    const newUser = enteredUser === "" ? "tab21" : enteredUser;
    setUser(newUser);
    console.log("user in search", newUser);
};

The problem with the code you are using is that the user state is not updated the first time you click. That's why a double click is required.

André
  • 1,602
  • 2
  • 12
  • 26