Kamran Tahir
Kamran Tahir

Reputation: 17

Redux dispatching only half of the functions

So, I want to directly replace the value of priority which is initially 1 to a different value. I created a redux function for it, but it's sending the function more than once.

Action

export const editPriority = (id, listID, newPriority) => {
  return {
    type: TRELLO_CONSTANTS.PRIORITY,
    payload: { id, listID, newPriority },
  };
};
      const { id, newPriority } = action.payload;
      const card = state[id];
      card.priority = newPriority;
      return { ...state, [`card-${id}`]: card };
    }

export const TRELLO_CONSTANTS = { PRIORITY: 'PRIORITY', };

and here's my function -

import {editPriority} from './actionTypes.js';

const card=({dispatch})=> {
  const [newPriority, priority] = useState(); 
}

const changePriority = (e) => {
    // newPriority(e);
    priority(e);
    dispatch(editPriority(id, listID, priority));
    console.log(priority);
  };

// and the main function


<button onClick={() => changePriority(1)}>1</button>
<button onClick={() => changePriority(2)}>0</button>

{priority === 0 ? <p>0</p> : null}
{priority === 1 ? <p>1</p> : null}

So whenever, I click the button, it only dispatches id and listID, not the priority. Plus I'm also not able to make the last 2 ternary operators work. Is this a wrong way to access them?

This is the output I get in redux extension -

{
  type: 'PRIORITY',
  payload: {
    id: 'card-0',
    listID: 'list-0'
  }
}

Upvotes: 1

Views: 41

Answers (1)

Jagrati
Jagrati

Reputation: 12222

You need to pass e directly to editPriority, since state updates are asynchronous in nature, and the change caused by priority(e) won't be reflected immediately.

const changePriority = (e) => {
    // newPriority(e);
    priority(e);
    dispatch(editPriority(id, listID, e));
 };

Suggestion:

In reducer, do not mutate the original state directly

const { id, newPriority } = action.payload;
const card = {...state[id]};
card.priority = newPriority;
return { ...state, [`card-${id}`]: card };

Also your priority state name is newPriority

So, use that value in render:

{newPriority === 0 ? <p>0</p> : null}
{newPriority === 1 ? <p>1</p> : null}

Suggestion: While naming your states you can use it as const [priority, setPriority] = useState(); to avoid the confustion

Upvotes: 1

Related Questions