Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

91
Visualizações
My state array gets emptied every time i call a function

I have this:

const BillsOverviewScreen = props => {
const { navigation } = props;

const [availableBills, setAvailableBills] = useState([]);

const bills = useSelector(state => state.bills.bills);

useEffect (() => {
    setAvailableBills(bills);
}, [bills]);


const dispatch = useDispatch();

useEffect(() => {
    dispatch(billsActions.loadBills());
}, [dispatch]);

React.useLayoutEffect(() => {
    navigation.setOptions({
        headerRight: () => (   
            <View style={{flexDirection:'row'}}>
                <SortingMenu sortBills={sortBills} />
                <FilterMenu />                   
            </View>                            

        ),
    });
  }, [navigation]);

function sortBills(sortBy) {
    
    switch (sortBy) {
        case 'title': {
             setAvailableBills(availableBills.sort((a, b) => a.title < b.title ? -1 : (a.title > b.title ? 1 : 0)))
            break;
        };
        case 'dateExpiry_up': {
             setAvailableBills(availableBills.sort((a,b) => new Date(b.dateExpiry) - new Date(a.dateExpiry)));  
            break;        
        };
        case 'dateExpiry_down': {
            setAvailableBills(availableBills.sort((a,b) => new Date(a.dateExpiry) - new Date(b.dateExpiry)));  
            break;          
        };
        case 'dateCreated_up': {
            setAvailableBills(availableBills.sort((a,b) => new Date(b.dateCreated) - new Date(a.dateCreated)));
            break;
        };
        case 'dateCreated_down': {
            setAvailableBills(availableBills.sort((a,b) => new Date(a.dateCreated) - new Date(b.dateCreated)));
            break;
        };
        default: 
            return availableBills
            
    }
}

Initially my state availableBills array gets filled as intended with the right data, but as soon as i use my sortBills function the array is empty. The weird thing is sometimes when i play around with it, its working. But when i reset my app its empty again. I really dont know what im doing wrong. tried different things but cant solve it.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

sort does an in-place mutation, so you are mutating the state and not really ever updating it.

sort

The sort() method sorts the elements of an array in place and returns the sorted array.

Shallow copy the state first, then sort it, using .slice easily creates a copy inline. I suggest using a functional state update for this. The functional state update avoids stale state enclosures by updating from the previous state versus the value of availableBills closed over in callback scope.

setAvailableBills(availableBills => 
  availableBills.slice().sort((a, b) => 
    a.title < b.title ? -1 : (a.title > b.title ? 1 : 0)
));

Apply this pattern across all your cases.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda