Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
¿Cómo declarar useState condicionalmente?

Para mi problema, en este momento estoy obteniendo datos de una API como esta.

 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; }); };

Como puede ver, obtengo 2 tipos de datos de una payload y un grupo de pago de paygroup debido al problema que encuentro en el componente.

Aquí está el componente

 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); //---------

Como puede ver en useState . Si quiero representar la lista de initial productList usando datos de payGroup , tengo que declarar como useState(hotProductGroup.Groups[0].Products) . El problema es que, este tipo de declaración siempre devuelve un error que indica que

undefined is not an object

Pero si quiero representar la lista de initial productList usando datos de la payload , este error no ocurre.

¿Qué debo hacer para que la declaration works para payGroup sin obtener un error?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Supongo que homeHotProductList es una matriz. Puede configurar su homeHotProductList en useEffect . Agregue hotProductList y hotProductGroup como dependencia para useEffect . Entonces, cada vez que estos valores cambien, puede configurar homeHotProductList usando setHomeHotProductList dentro useEffect condicionalmente.

 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])

Y con respecto a este error

indefinido no es un objeto

Puede usar el encadenamiento opcional o el operador coalescente nulo si no obtiene un valor como hotProductGroup?.Groups?.[0]?.Products ?? []

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!