-1

I'm new to react native development. And I have created this sample note application using Redux for react native. In this application user must be able to add a note and that note needs to be managed via redux store. And I have created required action and reducer for adding note functionality. However I was not able to add a new note to the store. I tried debugging and when it reaches the "ADD_Note" case in reducer, it jump into default case automatically. And whatever the string value or note that pass via action, it becomes 'undefined' in the reducer.

Please refer my code for adding note screen

import React, {useState, useEffect} from 'react';
import {
  StyleSheet,
  View,
  Text,
  TextInput,
  Button,
  FlatList,
} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import * as NoteActions from '../store/actions/Note'; // import note actions

const NoteScreen = () => {
  const [note, setNote] = useState('');

  const dispatch = useDispatch(); // use dispatch


  const noteHandler = text => {
    setNote(text);
  };


  return (
    <View style={styles.container}>
      <View>
        <TextInput
          style={styles.textInput}
          placeholder="Enter a note"
          onChangeText={noteHandler}
          value={note}
        />
        <Button
          title="Add"
          onPress={() => {
            console.log(note);
            dispatch(NoteActions.addNote(note));
          }}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: '100%',
    margin: 10,
  },
  textInput: {
    width: '100%',
    marginBottom: 10,
    textAlign: 'center',
    borderBottomWidth: 1,
  },
});

export default NoteScreen;

And below is the action js file.

// action types
export const ADD_NOTE = 'ADD_NOTE'

//action creators
export function addNote(note){
    return{
        type:ADD_NOTE,
        date:note
    }
}

And below is the reducer js file

// initial state
const initialState ={
    noteList:[]
}

// import actions
import ADD_NOTE from '../actions/Note';

function noteReducer (state=initialState, action){
    debugger;
    switch(action.type){
        case ADD_NOTE:
            const newNote = action.data
            return{
                ...state,
                noteList: state.noteList, newNote
            }
        default:
            return state;    
    }
}

export default noteReducer;

enter image description here

Please help me.

Thanks in advance, Yohan

1 Answers1

1

You need to add layer of dispatch at your action, also watch the typo date instead data


export const addNote = (note) => (dispatch, getState) => {
   return dispatch({
       type:ADD_NOTE,
       data :note 
     })
  }

Hagai Harari
  • 2,767
  • 3
  • 11
  • 23