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

122
Visualizações
How to declare useState conditonally?

For my problem , right now I am getting data from api like this.

const fetchSomething = () => dispatch => {
    return axios
        .get('productsapi/getsomething', {
        })
        .then(res => {
            dispatch({
                type: FETCH_SOMETHING,
                payload: res.data[0].Groups[0].Products,
                payGroup: res.data[0],
            });
        })
        .catch(err => {
            console.log('fetching error');
            throw err;
        });
};

As you can see I am getting 2 kind of data from an api payload and paygroup because of the problem I encountering in the component.

Here is the component

let hotProductList = useSelector(state => state.productReducer.hotProduct);
let hotProductGroup = useSelector(
        state => state.productReducer.newHotProductGroups,
);

const [homeHotProductList, setHomeHotProductList] = useState(hotProductGroup.Groups[0].Products);

//No Error
//---------
//const [homeHotProductList, setHomeHotProductList] = useState(hotProductList); 
//---------

As you can see in the useState. If I want to render the initial productList using data from payGroup I have to declare like useState(hotProductGroup.Groups[0].Products) . The problem is that, this kind of declaring always return error which state that

undefined is not an object

But If I want to render the initial productList using data from payload this error does not occur.

What Should I do to make the declaration works for the payGroup without getting error

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

0

I assume homeHotProductList is an array. You can set your homeHotProductList in useEffect. Add hotProductList and hotProductGroup as dependency to useEffect. So whenever these value changes you can set homeHotProductList using setHomeHotProductList inside useEffect conditionally.

let hotProductList = useSelector(state => state.productReducer.hotProduct);
let hotProductGroup = useSelector(
        state => state.productReducer.newHotProductGroups,
);

const [homeHotProductList, setHomeHotProductList] = useState([]);


useEffect(() => {
 // here you can set homeHotProductList conditionally

}, [hotProductList, hotProductGroup])

And regarding this error

undefined is not an object

You can use Optional chaining or Nullish coalescing operator if you're not getting value like hotProductGroup?.Groups?.[0]?.Products ?? []

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