Search code examples
react-nativereduxreact-reduxreducersredux-reducers

Update points Redux React Native


I'm trying to load points from Firebase in order to display it on the screen I'm using Redux, because the points number can be updated but I can not put this.props.Points.updatePoint inside Firebase request

How can I update it?

Home.js :

class Home extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     
    };
  }

  componentDidMount = async () => {
   const pointsRef=firebase.database().ref("Users").child(firebase.auth().currentUser.uid).orderByChild("Points").once('value',function(snapshot){
    const Points=snapshot.val().Points
    
   });
   this.props.Points.updatePoints(Points)


render(){
return(
     <Text>{this.props.Points}</Text>
)}
}



const mapStateToProps = (state) => {
  return {
    Points:state.Points};
};

const mapDispatchToProps = (dispatch) => {
  return {
    updatePoints:(Points)=>dispatch({ type: "UPDATE_POINTS", payload: Points }),
  };
};

PointReducer.js :

const initialState = {
    Points: 0,

  };
  
  const Points = (state = initialState, action) => {
    switch (action.type) {
        case "UPDATE_POINTS":
            return {
            ...state,
            Points: action.payload,
        };
        default:
            return state;
    }
  };
  
export default Points;
  

Solution

  • Your method is correct. The problem is actually with the way you're trying to access to updatePoints function in mapDispatchToProps & the place you're run the statement.

    class Home extends React.Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
    
      componentDidMount = async () => {
        const pointsRef = firebase
          .database()
          .ref("Users")
          .child(firebase.auth().currentUser.uid)
          .orderByChild("Points")
          .once("value", (snapshot) => {
            const Points = snapshot.val().Points;
            this.props.updatePoints(Points); // You can directly access to `updatePoints` using prop object.
          }); // convert this function to an arrow function. It will fix `this` related issues.
      };
    
      render() {
        return <Text>{this.props.Points}</Text>;
      }
    }
    
    const mapStateToProps = (state) => {
      return {
        Points: state.Points,
      };
    };
    
    const mapDispatchToProps = (dispatch) => {
      return {
        updatePoints: (Points) =>
          dispatch({ type: "UPDATE_POINTS", payload: Points }),
      };
    };
    

    Let me know if you need further support.