Add array into object with push

648 Views Asked by At

I'm practicing developing an app with react native. A simple toDo app. The problem is that I can't add tasks with an id as I get this error => Objects are not valid as a React child (found: object with keys {taskName, taskId}). If you want to render a collection of children, use an array instead. I don't understand what I'm doing wrong, if the constant taskToDo is equal to an object it tells me that taskToDo is not a function.

Probably or almost certainly the logic is not the most adequate, I also listen to suggestions.

This is my reduer

const initialState = {
    tasks: []
}


export const reducer = (state = initialState, action) => {
    switch (action.type) {
        case "ADD_TASK":
            return { ...state, tasks: [...state.tasks, action.payload] };
        case "COMPLETE_TASK":
            return {
                tasks: state.tasks.filter((task) => task !== action.payload)
            }

        default:
            return state
    }
}

Here the function

    const dispatch = useDispatch()
    const [taskName, setTaskName] = useState();
    const tasks = useSelector(state => state.tasks)

    const handleAddTask = () => {
        const taskToDo = []
        taskToDo.push({
            taskName: taskName,
            taskId: `id-${taskName}`
        })
        dispatch(addTask(taskToDo))
    }

And the button

 <KeyboardAvoidingView
    behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    style={styles.writeTaskWraper}
 >

        <TextInput
           placeholder='write a task'
           style={styles.input}
           onChangeText={text => setTaskName(text)}
           value={taskName}
        />

        <TouchableOpacity onPress={() => handleAddTask()}>
           <View style={styles.addWraper}>
              <Text style={styles.addText}>+</Text>
           </View>
        </TouchableOpacity>

 </KeyboardAvoidingView>

THANKS IN ADVANCE

1

There are 1 best solutions below

5
On BEST ANSWER

You are adding array of taskToDo[] to existing array in reducer. Try this way by adding new object to an array

const handleAddTask = () => {

    const taskToDo = {};

    taskToDo.taskName = taskName;
    taskToDo.taskId = `id-${taskName}`;
        
    dispatch(addTask(taskToDo))
}