Home > Software engineering >  React query - Why onSubmit only works after the second click
React query - Why onSubmit only works after the second click

Time:05-21

I have a simple React application in which I am trying to send a request to api with the parameter that the user will provide in input. My problem is that only after the second click on the button it'll returns data, the first click returns undefined.

React query hook -

import { useQuery } from "react-query";
import axios from 'axios';

const fetchFilteredsBooks = async (searchText: string) => {
    const res = await axios.get(`http://localhost:3001/api/book?search=${searchText}`);
    return res.data
}

export const useGetFilteredBooks = (searchText: string) => {
    return useQuery('filteredBooks', () => fetchFilteredsBooks(searchText), {
        enabled: false
    })
}

import styled from "styled-components"
import React, { useState } from "react"
import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks"



export const SearchBook = () => {
    const [text, setText] = useState('')
    const { data, refetch } = useGetFilteredBooks(text);

    const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setText(event.target.value)
    }

    const handleOnSubmit = (e: any) => {
        e.preventDefault();
        console.log(text);
        refetch();
        console.log(data);
    }


    return (
        <form onSubmit={handleOnSubmit}>
            <Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" />
            <button type="submit">Show</button>
        </form>
    )
}

const Input = styled.input`
    padding: 10px 10px;
    width: 300px;
`

CodePudding user response:

Because console.log(data) you call inside handleOnSumbit, move it to outside:

import styled from "styled-components"
import React, { useState } from "react"
import { useGetFilteredBooks } from "../../hooks/useGetFilteredBooks"



export const SearchBook = () => {
    const [text, setText] = useState('')
    const { data, refetch } = useGetFilteredBooks(text);

    const handleOnChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        setText(event.target.value)
    }

    const handleOnSubmit = (e: any) => {
        e.preventDefault();
        console.log(text);
        refetch();
    }

    console.log(data) //<== Move to here
    return (
        <form onSubmit={handleOnSubmit}>
            <Input value={text} onChange={handleOnChange} placeholder="Enter the name of the book or author" />
            <button type="submit">Show</button>
        </form>
    )
}

const Input = styled.input`
    padding: 10px 10px;
    width: 300px;
`

  • Related