lundi 8 février 2021

The state have value but when a function calls, the state have its default value

The screens render some CollapsibleViews with a Checkbox by the Text. When the user check or uncheck an checkbox, the function "onCheckboxSelect" is called, after this function, the state has a value diferent from the default one, but when the user tries to send the cheched information, the function "irConfValidade" is called, but when i try to acess the value of the state inside this function, the value is the default one (an empty array), i have no ideia how to fix this

import React, {useState, useEffect} from 'react'
import PropTypes from 'prop-types'
import {connect} from 'react-redux'

//Components
import LoadingSpinner from '../../../components/LoadingSpinner'

//Services/Modules
import Api from '../../../services/api'
import gActions from '../../../modules/redux/globalActions'

//Tags/Style
import {View, Text, ScrollView} from 'react-native'
import {Button} from 'react-native-elements'
import CheckBox from '@react-native-community/checkbox'
import CollapsibleView from '@eliav2/react-native-collapsible-view'
import globalStyles from '../../../modules/styles/globalStyles'

let ListaCategorias = (props) => {
    let {navigation, dispatch, reduxLogin, reduxServidor, reduxLocal, reduxAcao} = props

    let [categorias, setCategorias] = useState([])
    let [categoriasSelecionadas, setCategoriasSelecionadas] = useState([])
    let [isLoading, setLoading] = useState(false)

    useEffect(() => {
        let focusListener = navigation.addListener('focus', () => recuperarDados())
        navigation.setOptions({
            headerTitle: 'Lista de categorias',
            headerRight: () => (
                <Button
                    onPress={irConfValidade}
                    containerStyle=
                    title='Próximo'
                />
            )
        })

        return focusListener
    }, [navigation])

    let recuperarDados = async () => {
        setLoading(true)

        let data = {
            usuario: reduxLogin, 
            local: reduxLocal, 
            acao: reduxAcao
        }
        let url = `http://${reduxServidor}/ros/coletorApp/listarCategorias`
        let resp = await Api.postRequest(url, data)
        if(!resp.message && resp.length > 0)
            setCategorias(categorias = resp)
        if(!resp.message && resp.length == 0) {
            alert('Nenhuma conferência aprovada para o local selecionado')
            navigation.navigate('Locais Para Conferencia')
        }

        setLoading(false)
    }

    let onCheckboxSelected = (categoriaObj, value) => {
        let ids = [...categoriasSelecionadas]
        let categoria = categorias[categorias.indexOf(categoriaObj)]

        //Se for null, usuario escolheu categoria filho
        if(!categoria)
            categorias.forEach(({categoriasLvl2}) => {
                if(!categoria && categoriasLvl2.includes(categoriaObj))
                    categoria = categoriasLvl2[categoriasLvl2.indexOf(categoriaObj)]
            })

        if(value) {
            ids.push(categoria.id)
            if(categoria.categoriasLvl2)
                categoria.categoriasLvl2.forEach(catFilho => 
                    ids.push(catFilho.id)
                )
        } else {
            ids.splice(ids.indexOf(categoria.id), 1)
            if(categoria.categoriasLvl2)
                categoria.categoriasLvl2.forEach(catFilho =>
                    ids.splice(ids.indexOf(catFilho.id), 1)
                )
        }

        setCategoriasSelecionadas(ids)
    }

    let criarListItem = catePai => {
        let {id : idCatePai, nome, categoriasLvl2} = catePai
        return (
            <CollapsibleView
                style={globalStyles.grayBackground}
                title={
                    <View style=>
                        <CheckBox
                            value={categoriasSelecionadas.includes(idCatePai)}
                            onValueChange={value => onCheckboxSelected(catePai, value)}
                        />
                        <Text>{nome}</Text>
                    </View>
                }
                key={idCatePai}
            >
                {categoriasLvl2.map(catLvl2 => {
                    let {id :idCatFilho, nome} = catLvl2
                    return (
                        <View
                            key={idCatFilho}
                            style=
                        >
                            <CheckBox
                                value={categoriasSelecionadas.includes(idCatFilho)}
                                onValueChange={value => onCheckboxSelected(catLvl2, value)}
                            />
                            <Text>{nome}</Text>
                        </View>
                    )
                })}
            </CollapsibleView>
        )
    }

    let irConfValidade = () => {
        if(categoriasSelecionadas.length > 0) {
            dispatch(gActions.setReduxCategoria(categoriasSelecionadas))
            navigation.navigate('Produtos para conferência de validade')
        }
        else
            alert('Selecione ao menos 1 categoria')            
    }

    return(
        <View style={globalStyles.container}>
            <LoadingSpinner text={'Carregando...'} isVisible={isLoading}/>

            <ScrollView>
                {categorias.map(criarListItem)}
            </ScrollView>
        </View>
    )
}

ListaCategorias.propTypes = {
    navigation: PropTypes.object.isRequired,
    route: PropTypes.object.isRequired,
    dispatch: PropTypes.func.isRequired,
    reduxLogin: PropTypes.string.isRequired,
    reduxServidor: PropTypes.string.isRequired
}

let getReduxProps = state => {
    return({
        reduxLogin: state.login,
        reduxServidor: state.servidor,
        reduxLocal: state.local,
        reduxAcao: state.tipoAcao
    })
}

export default connect(getReduxProps)(ListaCategorias)



Aucun commentaire:

Enregistrer un commentaire