Home > other >  store the data that comes from backend into useState
store the data that comes from backend into useState

Time:10-28

I have a project and within this project I use TypeScript and React, but I encountered a problem that I want to store the response coming from the backend and put it in "setDataTraining" but the problem is that nothing is stored within this variable "dataTraining"

How can i solve this problem?

this is Response that comes from backend.

enter image description here

I tried using the following instruction:

committeeData?.items

And store it in the variable "dataTraining", but it didn't recognize the value of items even though it came from the backend.

index.tsx:

import _ from 'lodash';
import { FunctionComponent, useContext, useEffect, useState } from 'react';
import { Check } from 'react-feather';
import { useMutation, useQuery } from 'react-query';
import { useNavigate } from 'react-router-dom';
import caseServeice from '../../../api/nuclearMedicineApi/services/Case';
import {
    AuthContext,
    IAuthContext,
} from '../../../contexts/auth-context';
import Scaffold from '../../common/scaffold';
import { committeeRequestColumns } from './data';
import { committeeRequestFilters } from './filters';
import committeeRequest from '../../../api/nuclearMedicineApi/services/CommitteeRequests';
import { notify } from '../../common/notification';

interface CommitteeRequestPageProps { }

const CommitteeRequestPage: FunctionComponent<CommitteeRequestPageProps> = () => {
    const auth = useContext<IAuthContext>(AuthContext);

    let committeeColumns = committeeRequestColumns;
    committeeColumns = auth.userData?.roleNames?.some(
        (role) => role === 'DOCTOR',
    )
        ? committeeColumns.filter(
            (item) => item.dataSelector !== 'supervisoryDoctor',
        )
        : committeeColumns;

        const approveCommitteeRequestNotification = () => {
            // onSuccess: (data) => {
            notify('success', 'ok', 'approveCommitteeRequest');
            // },
        };

        const [dataTraining, setDataTraining] = useState({})
        const getDataFromBackend = async(waitingListId: any) =>{
            console.log('number: ', waitingListId, typeof(waitingListId)); 
            let dataPat = await committeeRequest.approveCommitteeRequest(waitingListId); 
            console.log('data training: ', dataTraining)
            console.log('getDataApprove: ', dataPat); 
            return dataPat; 
        }

       
        const getAllCommitteeData = async() => {
            let committeeData = await committeeRequest.comitteeRequestGetAll();
            setDataTraining(committeeData);
            console.log('committee Data Response: ', committeeData);
            console.log('data training: ', dataTraining); 
            return committeeData; 
        }

        useEffect(() => {
            getAllCommitteeData();
            setDataTraining((v) => v)
            console.log('data training outside: ', dataTraining)}, [dataTraining])


        // console.log('data training outside: ', dataTraining); 


        // useEffect(() => {
        //     committeeRequest.comitteeRequestGetAll()
        // }, []);


    return (
        <>
            <Scaffold
                getAllFunc={getAllCommitteeData}
                tableColumns={committeeColumns}
                filterColumns={committeeRequestFilters}
                getAllParams={{ MaxResultCount: 1000 }}
                create={false}
                fullWidthFrom
                dataName='committeeRequest'
                formType='full'
                update={false}
                restrictedActions={{ update: false }}
                // documentaionId={1}
                customCreateAction={() => {
                    // navigate('/auth/patient/create');
                } }
                customActions={[
                    {
                        Icon: <Check className='icon-button-table' />,
                        cb: (id) => {
                            console.log('iddddd: ', id)
                            let waitingListId =  id; 
                            console.log('idfgdg: ', waitingListId, typeof(waitingListId));
                            // setWaitingNumberId(waitingListId)
                            getDataFromBackend(waitingListId)
                            // committeeRequest.comitteeRequestGetAll()
                            // committeeRequest.approveCommitteeRequest(waitingListId)
                            // console.log('const a: ', a);
                            approveCommitteeRequestNotification()
                            
                        },
                        tooltip: 'Approve',
                    },
                ]}
                customOnRowClick={(row) => { } }
                FormSubmitMapper={(data) => data}
                mainPermissionName='Patient'
                tableDataMapper={(data) => {
                    return data?.map((row: any) => {
                        return {
                            ...row,
                            patient: row.patient?.label,
                            supervisoryDoctor: row.supervisoryDoctor?.label, 
                            topographyIndex: row.topographyIndex?.label, 
                            machine: row.machine?.label,

                        };
                    });
                } } createFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } } updateFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } } getFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } } deleteFunc={function (data: any): Promise<any> {
                    throw new Error('Function not implemented.');
                } }            />
        </>
    );
};

export default CommitteeRequestPage;

CodePudding user response:

Your code is probably working fine. You might have been confused by the console.log('data training: ', dataTraining) part.

If you want to see updated state values use a useEffect hook. You cannot use console.log to get the latest state value.

    const [dataTraining, setDataTraining] = useState<>()


    const getAllCommitteeData = async() => {
        let committeeData = await committeeRequest.comitteeRequestGetAll();
        setDataTraining(committeeData);
        console.log('committee Data Response: ', committeeData);
        console.log('data training: ', dataTraining); 
        return committeeData; 
    }

    useEffect(() => {console.log(dataTraining)}, [dataTraining])

Add this code and see the updated state value

CodePudding user response:

logging dataTraining right after setting will always log null, because dataTraining is filled after the (re)render of the screen, this needs some time.

To log dataTraining eventually you can do something like:

dataTraining && console.log(dataTraining);
  • Related