Using useState in React but not as I imagine

Asked

Viewed 75 times

-1

From what I understand useState, is using within the same function to update variable or html component within the same function.

What I need is:

I have a form and in it I need to call methods in another file. So far everything well, works. That is, go there in the database, search and bring the results and fill in the variable.

The problem is that it is not updating the component.

const FormularioPrincipalView = () => {

    const pivotPrincipal = useRef<Pivot | null>(null);
    const [listaPrincpal, setListaPrincpal] = useState([]);     

    const reportPrincipal = {
        dataSource: {
            data: listaPrincpal,
        },
        slice: {
            rows: [
            {uniqueName: "nome" },
            {uniqueName: "aniversario" }
            ]
        }
    };
    <Pivot
    ref={pivotPrincipal}
    toolbar
    report={reportPrincipal}
    height="450"
    />
}

The call is now like this:

export const pesquisaPrincipal = (item: PesquisaGusa) => {
    Promise.all([
    pesquisa(item).then(resp => {
        if (resp && resp.principal.length > 0) {
        pivotPrincipal.current.flexmonster.customizeCell(() => {});

        pivotPrincipal.current.flexmonster.setReport(pivotPrincipal.current.props.report);
        pivotPrincipal.current.flexmonster.customizeCell(customizeCellGusaPrincipalConvertedor);

        pivotMediaDesvioPadrao.current.flexmonster.setReport(pivotMediaDesvioPadrao.current.props.report);
        tamanhoDataPrincipalGusa = resp.contadorPrincipal;  
        }
    }),
    ]).then(() => {  
    isRegistros = false;
    });
}

How to solve or how best to use ?

1 answer

0

The example does not show what the Pivot component would be, but it is likely that the use of refs is unnecessary in this case (as it is in 99% of cases). Just like you can pass the state listPrincpal for child elements, you can also pass the function that modifies it setListaPrincpal. She’s always tied to that state and nothing else...

In the original element or in the child, you can make the API call and, if successful, use setListaPrincipal(resp.principal). At that moment, listPrincpal ceases to be an empty array and becomes a list of things you want to render. The parent element, and any child components you use listPrincpal as props, will be re-rendered with the new list.

Browser other questions tagged

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