My code looks like this:
import { SAVE_SEARCH } from '../actions/index';
export default function (state = [], action) {
switch (action.type) {
case SAVE_SEARCH:
return [...state, action.payloadTwo, action.payloadOne];
default:
return state;
}
}
And I'm getting such result in my state:
It works, but this is an array. I want to change it to object, like so:
case SAVE_SEARCH:
return [...state, { action.payloadTwo: action.payloadOne }];
So searchTerm would be the key in the object, and the data will be save as object key values.
But this code gives me an error:
I know it is obvious for you. Why I can't code it like this? Why I'm getting "Parsing Error"?
---------------
EDIT:
Many thanks to @marekful for his answer! Now it works!
My action.js code:
import axios from 'axios';
export const SAVE_SEARCH = 'SAVE_SEARCH';
export function searchTest(query) {
const githubApi = `https://api.github.com/search/repositories?q=${query}&sort=stars&order=desc`;
const request = axios.get(githubApi);
return (dispatch) => {
request.then(({ data: dataFromGithub }) => {
dispatch({ type: SAVE_SEARCH, payloadOne: query, payloadTwo: dataFromGithub });
});
};
}
reducer code:
import { SAVE_SEARCH } from '../actions/index';
export default function (state = [], action) {
switch (action.type) {
case SAVE_SEARCH:
const o = {};
o[action.payloadOne] = action.payloadTwo;
return [...state, o];
default:
return state;
}
}
Result:
In object literals, keys can only be string literals (values can be object references): {"someKey": object.property}
You can, however, use object references or function return values as object keys using array notation (but it still has to be a string):
let o = {};
o[action.payloadTwo] = action.payloadOne;
return [...state, o];