Doubt about useState refactoring when implementing the SWR?

Asked

Viewed 219 times

2

I’m starting in this world of Javascript and I have a project that I’m developing that I did the implementation of SWR in the same and with that I stopped using the useEffect and the useState of the main element that was the Inventories.

For the first rendering of the component this working 100% my problem is occurring in a function where I make a filter by Date and the return was placed in the state of the setInventorie and with it was rendered on the screen the inventories according to the survey.

I wonder how I can refactor my code of this function to fit and render this filter when necessary now that I am using the SWR, aiming that now the response.data that me is returning is not assigned to the state and with that, even doing the search correctly nothing is rendered on screen.

As it was without the SWR:

export default function Profile() {
    const [inventories, setInventories] = useState([]);
    const [selectedDate, handleDateChange] = useState('');
    const history = useHistory();
    moment.locale("pt-BR");

    useEffect(() => {
        axios.get('inventoryGroup', {
            headers: {
                Authorization: token,
            }
        }).then(response => {
            setInventories(response.data);
        });
    }, [token]);

    async function dataFilter(date) {
        handleDateChange(date);
        try{
            await axios.get(`/inventoryGroup?created_at=${moment(date).format("DD/MM/YYYY")}`).then(response => {
                if(response.data.length > 0) {
                    toast.success('Inventário encontrado.');
                    setInventories(response.data);
                } else {
                    toast.error('Nenhum inventário encontrado.');
                    axios.get(`/inventoryGroup`).then(response => {
                        setInventories(response.data);
                    })
                }
            })
        } catch(error) {
            toast.error(`Erro ao filtrar inventários ${error}`);
        }
    }
  
  return (
    <MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils} locale="pt-BR">
                <KeyboardDatePicker
                    value={selectedDate}
                    placeholder="Escolha uma data"
                    onChange={date => dataFilter(date)}
                    helperText={''}
                    format="DD/MM/yyyy"
                    error={null}
                />
     </MuiPickersUtilsProvider>
      
    {inventories.map(inventorie => (
                    <div>
                        <div className="separator"></div>
                        <tbody className="list-content" key={inventorie.id}>
                            <tr>      
                                <td>{inventorie.collector}</td>
                            </tr>

                            <tr>             
                                <td>{inventorie.count}</td>
                            </tr>
                            
                            <div className="inventorie-button">
                                <button onClick={() => collectorDetail(inventorie.collector)}
                                type="button" >
                                    <FiPlus scale={20} color="#a8a8b3" />
                                </button>

                                <button onClick={() => download_txt(inventorie.collector)}
                                type="button" >
                                    <FiDownload scale={20} color="#a8a8b3" />
                                </button>
                            </div>
                        </tbody>
                     </div>
                ))}
  )

As it is now with the SWR:

export default function Profile() {

    const [inventories, setInventories] = useState([]);

    const [selectedDate, handleDateChange] = useState('');

    const history = useHistory();

    moment.locale("pt-BR");

    const { data } = useFetch(inventories ? 'inventoryGroup' : false);
    

    if(!data) {
        return <p>Carregando...</p>
    }    
  
    async function dataFilter(date) {
        handleDateChange(date);
        try{
            await axios.get(`/inventoryGroup?created_at=${moment(date).format("DD/MM/YYYY")}`).then(response => {
                if(response.data.length > 0) {
                    toast.success('Inventário encontrado.');
                    setInventories(response.data);
                } else {
                    toast.error('Nenhum inventário encontrado.');
                    axios.get(`/inventoryGroup`).then(response => {
                    setInventories(response.data);
                    })
                }
            })
        } catch(error) {
            toast.error(`Erro ao filtrar inventários ${error}`);
        }
    }

    return (
        <div className="profile-container">
            <MuiPickersUtilsProvider libInstance={moment} utils={MomentUtils} locale="pt-BR">
                <KeyboardDatePicker
                    value={selectedDate}
                    placeholder="Escolha uma data"
                    onChange={date => dataFilter(date)}
                    helperText={''}
                    format="DD/MM/yyyy"
                    error={null}
                />
            </MuiPickersUtilsProvider>

            {<div className="inventorie-list">
                    <tbody className="list-title">
                            <tr>
                                <td>Coletor:</td>
                            </tr>
                            
                            <tr>
                                <td>Quantidade de Registros:</td>
                            </tr>
                    </tbody>
                
                {data.map(inventorie => (
                    <div>
                        <div className="separator"></div>
                        <tbody className="list-content" key={inventorie.id}>
                            <tr>      
                                <td>{inventorie.collector}</td>
                            </tr>

                            <tr>             
                                <td>{inventorie.count}</td>
                            </tr>
                            
                            <div className="inventorie-button">
                                <button onClick={() => collectorDetail(inventorie.collector)}
                                type="button" >
                                    <FiPlus scale={20} color="#a8a8b3" />
                                </button>

                                <button onClick={() => download_txt(inventorie.collector)}
                                type="button" >
                                    <FiDownload scale={20} color="#a8a8b3" />
                                </button>
                            </div>
                        </tbody>
                     </div>
                ))}
            </div>}
        </div>
    );
}

useFetch function that I import for use:

import useSWR from 'swr'
import axios from 'axios';

export function useFetch(url) {
  const { data, error, mutate } = useSWR(url, async url => {
    const response = await axios.get(url);

    return response.data;
  }, {
    refreshInterval: 1000,
    refreshWhenHidden: true
  })

  return { data, error, mutate }
}

Remembering that I am passing only the code of the parts from where my problem in the code really is.

  • Take a look at the edition, the code has to belong to your doubt.

  • 1

    Your question is very wide if you could have done so, created a minimum example with doubt and focus on what you need, the code is large and there is no way to test already seen external events.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.