Search code examples
reactjsreact-nativereduxredux-toolkit

React Redux toolkit - state management for input field


I am building an app in React Native and have begun to learn redux toolkit.

Previously I managed my states locally.

For some reason I cannot wrap my head around how to save the dynamic input of a text field using redux toolkit.

All examples I could find incorporate local (setState).

I have managed to handle all of my checkboxes as well as counters.. but I continue to receive errors when trying to handle my "onChangeText" function.

I am trying to populate the "odo" reading as 15 then allow the user to change it to whatever the correct number is. Currently my code returns "undefined did this work".

I've scoured the forums, official docs and youtube but cannot find any relevant example dealing with toolkit (dispatch/payload).

Thank you for any assistance!

//SLICE

import {
  createSlice
} from "@reduxjs/toolkit";

export const pickupInputSlice = createSlice({
  name: 'pickupInput',
  initialState: {
    odo: '15',
    waitTime: '11',
    notes: '12',
  },
  reducers: {
    odo: (state, action) => {
      state.odo = action.payload + "did this work";
    },
    waitTime: (state, action) => {
      state.waitTime = action.payload;
    },
    notes: (state, action) => {
      state.notes = action.payload;
    },
  }
});

export const {
  odo,
  waitTime,
  notes
} = pickupInputSlice.actions;

export default pickupInputSlice.reducer;


//SCREEN 

const odoReading = useSelector((state) => state.pickupInput.odo)


  <
  View >
  <
  Text style = {
    styles.checklistText
  } >
  Odometer Reading <
  /Text> <
  TextInput
style = {
  styles.checklistTextInput
}
autoCapitalize = 'none'
autoCorrect = {
  false
}
keyboardType = 'number-pad'
maxLength = {
  6
}
value = {
  odoReading
}
onChangeText = {
  () => dispatch(odo(odo.payload))
}
/> <
/View>


Solution

  • You have to pass value received from onChangeText to odo function

    <View>
      <Text style={styles.checklistText}>Odometer Reading </Text>
      <TextInput
        style={styles.checklistTextInput}
        autoCapitalize="none"
        autoCorrect={false}
        keyboardType="number-pad"
        maxLength={6}
        value={odoReading}
        onChangeText={value => dispatch(odo(value))} // pass value to reducer function as payload
      />
    </View>;