Update screen with reducer in react native

329 Views Asked by At

im trying to add a picture in the task, and after this, update the flatlist to see the update but it does not with. It works if I close and return on the app. If I display the store, I also see an instant update but not in my screen.

Here is a part of my code :

TaskImage.js


    openImageLibrary=async(task)=>{
      const result = await ImageHelpers.openImageLibrary();
      if(result){
        const downloadUrl=await this.uploadImage(result,task)
        this.props.UpdateTaskImage({...task,uri:downloadUrl})
      }
    }


....
const mapStateToProps=state=>{
    return{
      tasks:state.tasks
    };
  }
  
  const mapDispatchToProps=dispatch=>{
    return{
      loadTasks:tasks=> dispatch({type:'LOAD_TASKS_FROM_SERVER',payload:tasks}),
      addTask:task=>dispatch({type:'ADD_TASK',payload:task}),
      DeleteTask: task=>dispatch({type:'DELETE_TASK',payload:task}),
      UpdateTaskImage:task=>dispatch({type:'UPDATE_TASK_IMAGE',payload:task}) 
    }
  }

TasksReducer.js :

const initialState={
    tasks:[],
    image:null
}

const tasks=(state=initialState,action)=>{
    switch(action.type)
    {
        case 'LOAD_TASKS_FROM_SERVER':
            return{
                ...state,
                tasks:action.payload
            };
    case 'UPDATE_TASK_IMAGE':
        return{
            ...state,
            tasks:state.tasks.map(task=>{
            if(task.task==action.payload.task)
            {
                return {...task,image:action.payload.uri}
            }
            return task
            })
        }
        default:
            return state;
    }
};

export default tasks;

Any idea..?

1

There are 1 best solutions below

1
On

It would help to see more of your code, but here's what I think I'm seeing. How are the Flatlist items updated after the redux update? What I think may be your problem is that the Flatlist props are not also mapped to the redux state or directly passed down from this component's tasks prop. The Flatlist will re-render when its data prop is changed, so ensure that is the case.

Other than this consideration, ensure that in any case you're using redux correctly. I think you may be missing the call to the connect function. See the redux official doc, which uses this example:

// TodoList.js

function mapStateToProps(state) {
  const { todos } = state
  return { todoList: todos.allIds }
}

export default connect(mapStateToProps)(TodoList)