Home > Software design >  Using React Query and Flask to post and fetch
Using React Query and Flask to post and fetch

Time:07-07

I am trying to post some data from some input fields, send it to my Flask backend, and then have some new data returned to me.

Currently I do this with the regular fetch option, but I thought I might try simplifying my code a bit. However, I might just be stupid, or haven't found it, but I can't seem to figure out the way to do it with e.g. React Query (there are options like SWR as well I guess).

Right now my fetch function, that is called on a submit button, looks like:

const MyApp = () => {

    const returnObjects = {
        returnData1: [],
        returnData2: [],
        returnData3: [],
    };

    const [data, setData] = useState(returnObjects);
    const [loadingState, setLoadingState] = useState(false);

    function fetchData(e?: any) {
        e?.preventDefault();
        setLoadingState(true);
        fetch(`/api`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
               input1: inputOne
               input2: inputTwo,
           }),
        })
        .then(async (response) => {
            const json = await response.json();
            setData({
                returnData1: json.returnData1,
                returnData2: json.returnData2,
                returnData3: json.returnData3,
            });
            setLoadingState(false);
        });
    }

    const [inputOne, setInputOne] = useState(null);
    const [inputTwo, setInputTwo] = useState(null);

    return (
        <form onSubmit={fetchData}>
            <input type="number" value={inputOne} onChange={(e) => setInputOne(e.target.value)} />
            <input type="number" value={inputTwo} onChange={(e) => setInputTwo(e.target.value)} />
            <button type="submit">Fetch data</button>
        </form>

        <div>
            <p>{data.returnData1}</p>
            <p>{data.returnData2}</p>
            <p>{data.returnData3}</p>
        </div>
    )
}

export default MyApp;

So basically I post the data from my input fields, which is then given to the Flask backend, which does some calculations, and return the return data objects.

Again, can this be achieved with React Query as well, or...?

I've seen people using mutation and stuff, but then suddenly I don't think the code is that much cleaner to be honest. It's not like I need to store the data given as input at all. I just need some output from the backend depending on the input variables whenever I click the submit button.

CodePudding user response:

If you want to use react-query that way, you should pass the enabled option as false so it will execute only onSubmit.

This is how the react-query should look, the getData method is just a promise

  const { data, refetch } = useQuery(
    ["key", inputOne, inputTwo],
    getData(inputOne, inputTwo),
    { enabled: false }
  );

onSubmit you should call the refetch method

function fetchData() {
    refetch();
  }

example:

https://codesandbox.io/s/clever-frog-zo7hiu?file=/src/Form.js

  • Related