Home > Software engineering >  Updating a screen without reloading it
Updating a screen without reloading it

Time:04-21

I have a page where I update the information as soon as I click a 'Submit' button, and I want to update the information of the screen without having to reload the page.

This is the submit button:

import React from 'react';
import { useSaveOrderItemsForList } from '../../hooks/Lists/useSaveOrderItemsForList';
import ErrorIndicator from '../shared/ErrorIndicator';
import LoadingButton from '../shared/LoadingButton';
import { valueState as valueStateAtom } from '../../atoms/orderItemsAtom';
import { useSetRecoilState } from 'recoil';

export default function SaveOrderItemsButton({ orderItems, listID }) {
    const { isError, error, isLoading, mutate } = useSaveOrderItemsForList(orderItems, listID);
    const setValue = useSetRecoilState(valueStateAtom);

    return (
        <div className={'w-100'}>
            <br />
            <ErrorIndicator isError={isError} error={error} />
            <LoadingButton
                className={'w-100'}
                variant={'success'}
                loading={isLoading}
                onClick={() => {
                    mutate();
                    setValue([]);
                    window.location.reload();
                }}
            >
                Save
            </LoadingButton>
        </div>
    );
}

This is the useSaveOrderItemsForList custom hook:

import { getToken } from '../../tokens/getToken';
import { basePath } from '../../config/basePath';
import { getTokenAuthHeaders } from '../../functions/sharedHeaders';
import { useMutation, useQueryClient } from 'react-query';

async function saveOrderItemsForList({ orderItems, listID }) {
    const token = await getToken();
    const response = await fetch(`${basePath}/lists/save_order_items/${listID}`, {
        method: 'PUT',
        body: JSON.stringify({ orderItems }),
        headers: getTokenAuthHeaders(token)
    });

    return response.json();
}

export function useSaveOrderItemsForList(orderItems, listID) {
    const queryClient = useQueryClient();

    return useMutation(
        () => {
            return saveOrderItemsForList({ orderItems, listID });
        },
        {
            onSuccess: () => {
                return queryClient.invalidateQueries('lists');
            }
        }
    );
}

And this is the endpoint where the onClick event gets passed, and then loads the result:

router.put('/save_order_items/:id', TokenController.isAValidToken, async (req, res) => {
    const { orderItems } = req.body;

    try {
        const list = await ListsController.updateOrderItems(orderItems, req.params.id);
        res.json(list);
    } catch (error) {
        ErrorController.errorCallback(error, res);
    }
});

Is there a way I can achieve what I'm looking for, server or client side?

CodePudding user response:

In your top page component have this code:

const [, forceUpdate] = useReducer(x => x   1, 0);

  function handleClick() {
    forceUpdate();
  }

Send a click event back to the parent and handle the click by forcing the update.

  • Related