[Python] How to stop the state variables return from backend parameters from being overwritten...

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am performing a get request with a query parameter using axios in react/typescript. Backend is FastAPI/python and contains a sleep function (5 seconds) to simulate a delay in the request and then simply returns the same query parameter value.

    The request is triggered by a click event and the parameter is a state string set as the value of a text input field. The string returned from the API response is added to a state array and that indexes value is appended to the element displaying all the values in the array.

    When triggering the request twice in quick succession, the value of the second API response replaces the first response rather than being added to it and the array only has one entry rather than two and the first response value no longer exists.

    React request (user state is set as the value of a text input field)

    const [user, setUser] = useState<string>('')
    const [userArr, setUserArr] = useState<string[]>([])

    function handleChange(event: ChangeEvent<HTMLInputElement>) {
    setUser(event.target.value)
    }
    function handleButtonClick() {
    axios.get(`http://localhost:8000/api/q?user=${user}`)
    .then(response => response.data)
    .then((user) => {
    setUserArr([...userArr, user])
    })
    }

    return (
    <input type="text" value={user} onChange={handleChange} />
    <button onClick={handleButtonClick}>Submit</button>
    {
    userArr.map(user => (
    <div>{user}</div>
    ))
    }
    )


    API function

    @app.get('/api/q')
    def get_user(user: str):
    sleep(5)
    return user


    Scenario: Type "test 1" into the field and press the button. Shortly after (before the API response comes in), type "test 2" into the field and press the button again. Output will be "test 1" and then replaced with "test 2" rather than added after and displayed.

    Continue reading...

Compartilhe esta Página