Update array of object state in react js - javascript

I have the following code snippet from my component where I generate Input field according to the objects in the state.
I can successfully generate the input fields but have been getting error message:
TypeError: Cannot read property 'map' of undefined
Pointing to the method arrayObjToArrary in Utils.js whenever I type in the input field.
How can I update the value of here ??
Main.js
import Input from "../UI/Input";
import {arrayObjToArrary} from "../../utility/Utils.js";
const [profiles, setProfiles] = useState({
controls: [
{
network: {
elementType: "input",
elementConfig: {
type: "text",
label: "Network",
},
value: "Twitter",
},
},
{
username: {
elementType: "input",
elementConfig: {
type: "text",
label: "Username",
},
value: "#john",
},
},
{
url: {
elementType: "input",
elementConfig: {
type: "url",
label: "URL",
},
value: "https://example.xyz",
},
},
],
});
const profilesControls = arrayObjToArrary(profiles.controls);
const arrayInputHandler = (event, index, identifier) => {
const list = [...profiles.controls];
list[index][identifier] = event.target.value;
setProfiles(list);
};
let profileField = profilesControls.map((formElement) => (
<Input
label={formElement.config.elementConfig.label}
key={formElement.index}
type={formElement.config.elementType}
elementConfig={formElement.config.elementConfig}
value={formElement.config.value}
changed={(event) => arrayInputHandler(event, formElement.index, formElement.id)}
/>
));
Utils.js
export const arrayObjToArrary = (controls) => {
const formElementsArray = controls.map((item,index) =>({
id: Object.keys(item)[0],
index:index,
config: item[Object.keys(item)[0]],
}))
return formElementsArray;
}

You can try this
const arrayInputHandler = (event, index, identifier) => {
const list = [...profiles.controls];
list[index][identifier].value = event.target.value;
setProfiles({ controls: list });
};
check here codesandbox

The issue in how you update your profiles object in arrayInputHandler. When you pass in the list to setProfiles, it changes its structure from an object to array.
Also you must not mutate the original state values. The correct way to update is as below
const arrayInputHandler = (event, index, identifier) => {
const value = event.target.value;
setProfiles(prev => ({
...prev,
controls: profiles.controls.map((controls, i) => {
if(i === index) {
return {
...controls, [identifier]: {
...controls[identifier],
value
}
}
}
return controls
});
}));
};
P.S. You can always solve your problem in a simplistic manner like
const arrayInputHandler = (event, index, identifier) => {
const list = [...profiles.controls];
list[index][identifier] = event.target.value;
setProfiles({profile:list});
};
However its not a correct approach and should be avoided as react relies a lot on immutability for a lot of its re-rendering and other optimizations

Related

Quasar QSelect is not opening when performing AJAX call

I have been trying to create a simple auto complete using Quasar's select but I'm not sure if this is a bug or if I'm doing something wrong.
Problem
Whenever I click the QSelect component, it doesn't show the dropdown where I can pick the options from.
video of the problem
As soon as I click on the QSelect component, I make a request to fetch a list of 50 tags, then I populate the tags to my QSelect but the dropdown doesn't show.
Code
import type { PropType } from "vue";
import { defineComponent, h, ref } from "vue";
import type { TagCodec } from "#/services/api/resources/tags/codec";
import { list } from "#/services/api/resources/tags/actions";
import { QSelect } from "quasar";
export const TagAutoComplete = defineComponent({
name: "TagAutoComplete",
props: {
modelValue: { type: Array as PropType<TagCodec[]> },
},
emits: ["update:modelValue"],
setup(props, context) {
const loading = ref(false);
const tags = ref<TagCodec[]>([]);
// eslint-disable-next-line #typescript-eslint/ban-types
const onFilterTest = (val: string, doneFn: (update: Function) => void) => {
const parameters = val === "" ? {} : { title: val };
doneFn(async () => {
loading.value = true;
const response = await list(parameters);
if (val) {
const needle = val.toLowerCase();
tags.value = response.data.data.filter(
(tag) => tag.title.toLowerCase().indexOf(needle) > -1
);
} else {
tags.value = response.data.data;
}
loading.value = false;
});
};
const onInput = (values: TagCodec[]) => {
context.emit("update:modelValue", values);
};
return function render() {
return h(QSelect, {
modelValue: props.modelValue,
multiple: true,
options: tags.value,
dense: true,
optionLabel: "title",
optionValue: "id",
outlined: true,
useInput: true,
useChips: true,
placeholder: "Start typing to search",
onFilter: onFilterTest,
"onUpdate:modelValue": onInput,
loading: loading.value,
});
};
},
});
What I have tried
I have tried to use the several props that is available for the component but nothing seemed to work.
My understanding is that whenever we want to create an AJAX request using QSelect we should use the onFilter event emitted by QSelect and handle the case from there.
Questions
Is this the way to create a Quasar AJAX Autocomplete? (I have tried to search online but all the answers are in Quasar's forums that are currently returning BAD GATEWAY)
What am I doing wrong that it is not displaying the dropdown as soon as I click on the QSelect?
It seems updateFn may not allow being async. Shift the async action a level up to solve the issue.
const onFilterTest = async (val, update /* abort */) => {
const parameters = val === '' ? {} : { title: val };
loading.value = true;
const response = await list(parameters);
let list = response.data.data;
if (val) {
const needle = val.toLowerCase();
list = response.data.data.filter((x) => x.title.toLowerCase()
.includes(needle));
}
update(() => {
tags.value = list;
loading.value = false;
});
};
I tested it by the following code and mocked values.
// import type { PropType } from 'vue';
import { defineComponent, h, ref } from 'vue';
// import type { TagCodec } from "#/services/api/resources/tags/codec";
// import { list } from "#/services/api/resources/tags/actions";
import { QSelect } from 'quasar';
export const TagAutoComplete = defineComponent({
name: 'TagAutoComplete',
props: {
modelValue: { type: [] },
},
emits: ['update:modelValue'],
setup(props, context) {
const loading = ref(false);
const tags = ref([]);
const onFilterTest = async (val, update /* abort */) => {
// const parameters = val === '' ? {} : { title: val };
loading.value = true;
const response = await new Promise((resolve) => {
setTimeout(() => {
resolve({
data: {
data: [
{
id: 1,
title: 'Vue',
},
{
id: 2,
title: 'Vuex',
},
{
id: 3,
title: 'Nuxt',
},
{
id: 4,
title: 'SSR',
},
],
},
});
}, 3000);
});
let list = response.data.data;
if (val) {
const needle = val.toLowerCase();
list = response.data.data.filter((x) => x.title.toLowerCase()
.includes(needle));
}
update(() => {
tags.value = list;
loading.value = false;
});
};
const onInput = (values) => {
context.emit('update:modelValue', values);
};
return function render() {
return h(QSelect, {
modelValue: props.modelValue,
multiple: true,
options: tags.value,
dense: true,
optionLabel: 'title',
optionValue: 'id',
outlined: true,
useInput: true,
useChips: true,
placeholder: 'Start typing to search',
onFilter: onFilterTest,
'onUpdate:modelValue': onInput,
loading: loading.value,
});
};
},
});

SetState of an Objects of array in React

So i've been working on this for awhile what i'm trying to do is change a checked value on checkbox click.
My initial state looks like this:
const [todoList, setTodoList] = useState({
foundation: {
steps: [
{ key: "1", title: "setup virtual office", isDone: false },
{ key: "2", title: "set mission and vision", isDone: false },
{ key: "3", title: "select business name", isDone: false },
{ key: "4", title: "buy domain", isDone: false },
],
},
discovery: {
steps: [
{ key: "1", title: "create roadmap", isDone: false },
{ key: "2", title: "competitor analysis", isDone: false },
],
}
});
and my map and onClick function (updateCheckFoundation works when click the checkbox)
{todoList.foundation.steps.map((item) => {
return (
<div>
<input type="checkbox" defaultChecked={item.isDone}
onClick={(event)=> updateCheckFoundation({
isDone:event.target.checked,
key:item.key
})}/>
<span>{item.title}</span>
</div>
);
})}
so how can ı update todoList use setState?
my code (updateCheckFoundation func.) like this and is not working :( :
const updateCheckFoundation = ({isDone, key}) => {
const updateTodoList = todoList.foundation.steps.map((todo)=> {
if(todo.key === key){
return {
...todo,
isDone
};
}
return todo;
});
setTodoList(updateTodoList);
}
Issue
Your updateCheckFoundation callback isn't maintaining the state invariant, and is in fact, dropping all but the foundation.steps array of state.
const updateCheckFoundation = ({isDone, key}) => {
const updateTodoList = todoList.foundation.steps.map((todo)=> {
if(todo.key === key){
return {
...todo,
isDone
};
}
return todo;
});
setTodoList(updateTodoList); // <-- only the state.foundation.steps array!!
}
Solution
In function components, when using the useState state updater functions you need to handle merging state (the root state), and nested state, yourself, manually.
const updateCheckFoundation = ({ isDone, key }) => {
setTodoList(state => ({
...state, // <-- shallow copy state object
foundation: {
...state.foundation, // <-- shallow copy
steps: state.foundation.steps.map(todo => todo.key === key
? { ...todo, isDone }
: todo)
},
}));
}

Having problem in accessing values from state when traversing an array

i'm trying to traverse an Array and perform some operation. But cann't access the values as i want to.
inputObj.map(el => {
const msg = this.state.validation[el.id].message;
const msg2 = this.state.validation['name'].message;
})
Here, el.id can be name, dob or address. When i use this.state.validation[el.id].message;, it shows TypeError: Cannot read property 'message' of undefined. But if i hardcode it like this.state.validation['name'].message;, it works fine. when comparing both el.id and 'name', they have same datatype and same value. So, why having problem when using el.id instead of hardcoding it.
NB: i'm using reactjs.
Edit:
this.state:
this.state = {
super(props);
this.validator = new FormValidator([
{
field: 'name',
method: 'isEmpty',
validWhen: false,
message: 'Name is required'
},
...
]);
orderForm: {
name: {
elementType: 'input',
elementConfig: ''
},
...
}
validation: this.validator.setValid() // it will be the updated upon submitting form on submitHandler by calling validate() from FormValidator
}
inputObj:
const inputObj= [];
for(let key in this.state.orderForm){
inputObj.push({
id : key,
config: this.state.orderForm[key]
});
}
FormValidator
import validator from 'validator';
class FormValidator {
constructor(rules){
this.rules = rules;
}
setValid(){
const validation = {};
this.rules.map(rule => (
validation[rule.field] = {isValid: true, message: ''}
));
return {isValid: true, ...validation};
}
validate(form){
let validation = this.setValid();
this.rules.forEach( rule => {
if (validation[rule.field].isValid){
const field = form[rule.field].toString();
const args = rule.args || [];
const validationMethod = typeof rule.method === 'string' ?
validator[rule.method] : rule.method;
if (validationMethod(field, ...args, form) !== rule.validWhen){
validation[rule.field] = {isValid: false, message: rule.message};
validation.isValid = false;
}
}
});
return validation;
}
}
export default FormValidator;
You can check if this.state.validation[el.id] is defined before getting message key.
Like that you can't get fatal error.
inputObj.map(el => {
this.state.validation[el.id] && (
const msg = this.state.validation[el.id].message
);
})

In React/Redux reducer, how can I update a string in an nested array in an immutable way?

My store looks like this,
{
name: "john",
foo: {},
arr: [
{
id:101,
desc:'comment'
},
{
id:101,
desc:'comment2'
}
]
}
My textarea looks like this
<textarea
id={arr.id} //"101"
name={`tesc:`}
value={this.props.store.desc}
onChange={this.props.onChng}
/>
My action is
export const onChng = (desc) => ({
type: Constants.SET_DESC,
payload: {
desc
}
});
My reducer
case Constants.SET_DESC:
return update(state, {
store: {
streams: {
desc: { $set: action.payload.desc }
}
}
});
It works only if arry is an object, I had to make changes to the stream to an array and I am confused how I can update to an array, also how does get the right value from the store.
The following example taken from the redux documentation might help you in the use case how to update items in an array. For more on this you can read on here http://redux.js.org/docs/recipes/StructuringReducers.html
state structure is something like this
{
visibilityFilter: 'SHOW_ALL',
todos: [
{
text: 'Consider using Redux',
completed: true,
},
{
text: 'Keep all state in a single tree',
completed: false
}
]
}
and reducer code is like below
function updateObject(oldObject, newValues) {
// Encapsulate the idea of passing a new object as the first parameter
// to Object.assign to ensure we correctly copy data instead of mutating
return Object.assign({}, oldObject, newValues);
}
function updateItemInArray(array, itemId, updateItemCallback) {
const updatedItems = array.map(item => {
if(item.id !== itemId) {
// Since we only want to update one item, preserve all others as they are now
return item;
}
// Use the provided callback to create an updated item
const updatedItem = updateItemCallback(item);
return updatedItem;
});
return updatedItems;
}
function appReducer(state = initialState, action) {
switch(action.type) {
case 'EDIT_TODO' : {
const newTodos = updateItemInArray(state.todos, action.id, todo => {
return updateObject(todo, {text : action.text});
});
return updateObject(state, {todos : newTodos});
}
default : return state;
}
}
If you have to update an element in a array within your store you have to copy the array and clone the matching element to apply your changes.
So in the first step your action should contain either the already cloned (and changed) object or the id of the object and the properties to change.
Here is a rough example:
export class MyActions {
static readonly UPDATE_ITEM = 'My.Action.UPDATE_ITEM';
static updateItem(id: string, changedValues: any) {
return { type: MyActions.UPDATE_ITEM, payload: { id, changedValues } };
}
}
export const myReducer: Reducer<IAppState> = (state: IAppState = initialState, action: AnyAction): IAppState => {
switch (action.type) {
case MyActions.UPDATE_ITEM:
return { ...state, items: merge(state.items, action.payload) };
default:
return state;
}
}
const merge = (array, change) => {
// check if an item with the id already exists
const index = array.findIndex(item => item.id === change.id);
// copy the source array
array = [...array];
if(index >= 0) {
// clone and change the existing item
const existingItem = array[index];
array[index] = { ...existingItem, ...change.changedValues };
} else {
// add a new item to the array
array.push = { id: change.id, ...change.changedValues };
}
return array;
}
To update an array, I would use immutability helper and do something like this - to your reducer
let store = {"state" : {
"data": [{
"subset": [{
"id": 1
}, {
"id": 2
}]
}, {
"subset": [{
"id": 10
}, {
"id": 11
}, {
"id": 12
}]
}]
}}
case Constants.SET_DESC:
return update(store, {
"state" : {
"data": {
[action.indexToUpdate]: {
"subset": {
$set: action.payload.desc
}
}
}
}
})
});

React.DOM: Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

Being a newbie to the React community...I'm blocked (for hours now) and unable to trace a solution to fix the error posted above:
Am I missing the right parameters to how the data object is fetched in through the app?
This is my ajax data response
The bug is living on props.personList.map inside of const ListContainer
For context here's the code on the entire file:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
function getPersonList() {
const api = 'apistring';
return axios.get(api).then(res => {
console.log(res);
}).catch(err => console.log(err));
}
let getLastName = (fullName) => {
return fullName.match(/\w+/g)[1];
};
const getFirstName = (fullName) => {
return fullName.match(/\w+/g)[0];
};
//Remove any people that do not have the name we are searching for
let filterByName = (searchForName, personList) => {
return personList.filter((person) => {
return person.name === searchForName;
});
};
//VIEW (React)
const Search = ({ onChange }) => React.DOM.input({
type: 'input',
onChange
});
const Thumbnail = ({src}) => React.DOM.img({
className: 'image',
src
});
//CODE BREAKS HERE
const ListRow = (props) => React.DOM.tr({ key: props.person.name }, [
React.DOM.td({ key: 'headshot' }, React.createElement(Thumbnail, { src: props.person.url })),
React.DOM.td({ key: 'firstName' }, null, getFirstName(props.person.name)),
React.DOM.td({ key: 'lastName' }, null, getLastName(props.person.name)),
]);
const ListContainer = (props) => React.DOM.table({ className: 'list-container' }, [
React.DOM.thead({ key: 'firstName' }, React.DOM.tr({}, [
React.DOM.th({ key: 'lastName' }, null, 'headshot'),
React.DOM.th({ key: 'id' }, null, 'First Name'),
React.DOM.th({ key: 'last-h' }, null, 'Last Name')
])),
React.DOM.tbody({ key: 'tbody' }, props.personList.map((person, i) =>
React.createElement(ListRow, { key: `person-${i}`, person })))
]);
const App = React.createClass({
getInitialState() {
return {
personList: [],
visiblePersonList: []
};
},
componentDidMount() {
getPersonList().then((data) =>
this.setState({
data,
visiblePersonList: data
}));
},
_shuffleList() {
this.setState({
visiblePersonList: shuffleList(this.state.personList)
});
},
_sortByFirst() {
this.setState({
visiblePersonList: sortByFirstName(this.state.personList)
});
},
_sortByLast() {
this.setState({
visiblePersonList: sortByLastName(this.state.personList)
});
},
_onSearch(e) {
this.setState({
visiblePersonList: filterByName(e.target.value, this.state.personList)
});
},
render() {
const { visiblePersonList } = this.state;
return React.DOM.div({ className: 'app-container' }, [
React.createElement(Search, { key: 'search', onChange: this._onSearch }),
React.DOM.button({ key: 'shuffle', onClick: this._shuffleList }, null, 'Shuffle'),
React.DOM.button({ key: 'sort-first', onClick: this._sortByFirst }, null, 'Sort (First Name)'),
React.DOM.button({ key: 'sort-last', onClick: this._sortByLast }, null, 'Sort (Last Name)'),
React.createElement(ListContainer, { key: 'list', personList: visiblePersonList })
]);
}
});
ReactDOM.render(<App />, document.getElementById('app'));
Your callback with the console.log accesses the value and then discards it.
function getPersonList() {
const api = 'apistring';
return axios.get(api).then(res => {
console.log(res);
}).catch(err => console.log(err));
}
should be
function getPersonList() {
const api = 'apistring';
return axios.get(api).then(res => {
console.log(res);
return res.data.items;
}).catch(err => console.log(err));
}
When you use .then you are inserting a link into your promise chain. The value returned by .then becomes the value passed to the next handler. Because you are not returning any value, your
getPersonList().then((data) => {
// ...
});
callback will get data as undefined.
Another thing to note, though don't cause this specific error, is that your screenshot shows objects with .firstName and .lastName but all of the code in this file uses .name which does not exist.

Categories