Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - Why is redux State no updating?

I have a Redux Action but I can′t make it work . I need to find the index of an object which nested into an array of a firebase collection. After getting the data from the DB, I calculate the index but can′t send it to redux. It′s probably a super noob JavaScript mistake, I don′t know why but i can′t update the object that I am sending to redux (reDatos)

export const calcularIdsAModificar = (MOid) => {
  let reDatos = {
    MOid: MOid,
    MOidindex: null,
  };

  return (dispatch, getState, { getFirebase, getFirestore }) => {
    const Firestore = getFirestore();
    const authorId = getState().firebase.auth.uid;
    let experienciasArray = 'sin datos';

    Firestore.collection('users')
      .doc(authorId)
      .get()
      .then((resp) => {
        experienciasArray = resp.data().experiencia;
        let newindex = experienciasArray.findIndex((expe) => expe.id === MOid);
        reDatos['MOidindex'] = newindex;
      })

      .then(dispatch({ type: 'ONCLICK_EDITAR_EXPERIENCIA', reDatos: reDatos }));
  };
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the problem: the second then gets called imediatelly when the function is declared. For it to work, you need to pass handler (arrow function or funciton declaration) to the then.

Another thing to note here is that you don't actually need the second then. Since the code inside the first then is synchronous, you could call the dispatch inside it.

 return (dispatch, getState, {getFirebase, getFirestore}) => {

       const Firestore = getFirestore();
       const authorId = getState().firebase.auth.uid;
       let experienciasArray = 'sin datos'
      
       

       Firestore.collection('users').doc(authorId).get().then(resp =>  {
           
        experienciasArray = resp.data().experiencia          
        let newindex = experienciasArray.findIndex(expe => expe.id === MOid)
        reDatos['MOidindex'] = newindex

        dispatch({ type:'ONCLICK_EDITAR_EXPERIENCIA', reDatos: reDatos })    

       });
      
        //.then(() => ?{dispatch...}); //Or call a dispatch inside an arrow function here.  

    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...