0
const [text, setText] = useState('');
useEffect(() => async () => {
  try {
    const response = await axios.post(
      'http://localhost:3001/changed',
      { text: text },
      { withCredentials: true }
    );
    console.log(response.data.text);
  } 
  catch (e) { 
    console.log(e);
  }
}, [text]);

I also have a text input like this:

<input type="text" onChange={ (e) => setText(e.target.value) } />

The backend is returning the same posted object. The problem is that when I input the first character the useEffect logs an empty string and when I input the second character the useEffect logs the first character only.

When I input the third character in the input field the useEffect logs the first two characters. It is lagging behind by one character. Why this is happening?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
VELDAS R DURAI
  • 301
  • 4
  • 9

2 Answers2

0

That's because instead of calling the async function in the useEffect-hook, you are returning it. That means it gets called after the text variable changes the next time.

Try this instead:

// declare the function somewhere OUTSIDE your component
async function f(test) {  
  try {
    const response = await axios.post( 
      http://localhost:3001/changed`, 
      {text}, 
      {withCredentials: true}
    );
    console.log(response.data.text);
  } 
  catch (e) { 
    console.log(e);
  }
}

// and in your component:

const [text , setText] = useState("");

useEffect(() => {
  f(text);    // call it and don't return anything
}, [text]);

https://reactjs.org/docs/hooks-effect.html

HumanCatfood
  • 960
  • 1
  • 7
  • 20
0

you can simply do like this: working demo

export default function App() {
  const [text, setText] = useState("");
  useEffect(() => {
    console.log("number is", text);
    async function makeCall() {
      try {
        const response = await axios.post(
          `http://localhost:3001/changed`,
          { text: text },
          { withCredentials: true }
        );
        console.log(response.data.text);
      } catch (e) {
        console.log(e);
      }
    }
    makeCall();
  }, [text]);

  return (
    <div className="App">
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
      />
    </div>
  );
}
Amaresh S M
  • 2,936
  • 2
  • 13
  • 25