Howcome form value does not reset? - reactjs

I have a form.
This returns back and loads its value which is correct,
however when I start typing it only returns its value plus one letter from the onChange.
here is what I mean
How do I clear the value of the form when the onChange is executed? I have tried clearing the form using config.setStateVar('') which still does not seem to work. Does anyone have any ideas?
const onChange = (e, config) => {
config.setStateVar('')
const value = e.target.innertext ? e.target.innertext
: e.target.value
config.setStateVar(value)
}
Full Code:
const editCriticalObjects = props => {
const query = new URLSearchParams(props.location.search)
const criticalObjectsId = query.get('id')
const loading = useContext(LoadingContext)
const user = useContext(UserContext)
const [editCriticalObjects, setEditCriticalObjects] = useState([])
const [criticalObjectTitle, setCriticalObjectTitle] = useState('')
const [criticalObjectDomainName, setCriticalObjectDomainName] = useState('')
const [criticalObjectType, setCriticalObjectType] = useState('')
const [findVal, setFindVal] = useState('')
useEffect(() => {
async function onLoadCriticalObjects() {
loading.setLoading(true)
const results = await get(`get_critical_objects?id=${criticalObjectsId}`, user.user)
setEditCriticalObjects(results)
loading.setLoading(false)
}
onLoadCriticalObjects()
}, [])
const assetIdObject = editCriticalObjects.filter(obj => {
if (obj.asset_id === criticalObjectsId) {
return obj
}
return assetIdObject
})
const configs = [
{
label: 'Title',
name: 'Title',
value: assetIdObject.map(item => item.asset_id),
field: SinglelineTextfield,
uniqueIdentifier: 0,
stateVar: criticalObjectTitle,
setStateVar: setCriticalObjectTitle,
},
{
name: 'type',
uniqueIdentifier: 1,
label: 'type',
value: assetIdObject.map(item => item.type),
field: SinglelineTextfield,
stateVar: criticalObjectType,
setStateVar: setCriticalObjectType,
},
{
name: 'Domain',
label: 'Domain',
value: assetIdObject.map(item => item.Domains),
field: SinglelineTextfield,
uniqueIdentifier: 2,
stateVar: criticalObjectDomainName,
setStateVar: setCriticalObjectDomainName,
}
]
const criticalObjectParams = {
asset_ids: criticalObjectTitle,
asset: true,
merge: true,
}
console.log(criticalObjectParams)
const onChange = (e, config) => {
const value = e.target.innertext ? e.target.innertext
: e.target.value
config.setStateVar(value)
}
const onSubmitClick = async () => {
loading.setLoading(true)
await verifiedPost('post_critical_objects', criticalObjectParams, user.user)
loading.setLoading(false)
}
return (!editCriticalObjects ? null :
<PageWrapper title={`Edit Critical Object: ${criticalObjectsId}`}>
<div className='Main Card EditCriticalObjectFormWrapper'>
{configs.map((config, k)=> {
const Field = config.field
return (
<React.Fragment key={k}>
<Field
style={{ marginBottom: '15px'}}
name={config.name}
placeholder={config.name}
value={config.value}
initialValue={config.value}
initialValues={config.value}
uniqueIdentifier={k}
label={config.label}
onChange={(e) => onChange(e, config)}
/>
</React.Fragment>
)
})}
<Button
className='Button Dark Main'
text='Submit'
onClick={onSubmitClick}
/>
</div>
</PageWrapper>
)
}
export default editCriticalObjects

Related

react-checkbox-tree not checked with children issue

I am using react checkbox tree package. I have a treeview with checkbox as below.
const nodes = [
{
value: "mars",
label: "Mars",
children: [
{
value: "phobos",
label: "Phobos"
},
{ value: "deimos", label: "Deimos" }
]
},
{
value: "saturn",
label: "Satrun"
},
{
value: "jupitor",
label: "Jupitor"
}
];
function Widget() {
const [checked, setChecked] = useState([]);
const [expanded, setExpanded] = useState([]);
const updateCheckedState = (node) => {
const childValues = [];
const isParent = node.isParent;
const updatedValues = isParent ? childValues : [node.value];
if (node.checked) {
setChecked([...updatedValues]);
} else {
const filteredChecks = checked.filter((check) => {
return !updatedValues.includes(check);
});
setChecked(filteredChecks);
}
};
return (
<CheckboxTree
iconsClass="fa5"
nodes={nodes}
checked={checked}
expanded={expanded}
onCheck={(nodes, node) => {
updateCheckedState(node);
}}
onExpand={(expanded) => setExpanded(expanded)}
/>
);
}
Full example is here
My issue is when I clicked checkbox with children it doesn't checked(example Mars). But I clicked no children element then it checked. Please help me to fix this.
checked is the array of node values, so you will need to assign the children's values.
const updatedValues = isParent
? node.children.map((v) => v.value)
: [node.value];

Unable to use value of useRef in value of input in react native

I have a dropdown based on which different fields gets rendered. Initially I have initialized selected option of dropdown in useEffect hook, corresponding fields gets rendered and are working fine.
But when different option or even same option is chosen from dropdown fields gets rendered but when I type something in it it gets cleared. I have used useRef to store values for field at index i in fields array.
export default function CreateEntry({ navigation }) {
const { user, setLoading, setLoadingMsg } = useAuthContext();
const [name, setName] = useState("");
const [selectedCategory, setSelectedCategory] = useState("");
const [categoriesList, setCategoriesList] = useState([]);
const [primary, setPrimary] = useState("");
const [primaryValue, setPrimaryValue] = useState("");
const [fields, setFields] = useState([
{
name: "Email",
value: "",
type: "string",
encrypt: false,
},
{
name: "Password",
value: "",
type: "string",
encrypt: true,
},
]);
const refInputs = useRef([]);
useEffect(() => {
firestore()
.collection("categories")
.doc(user.uid)
.get()
.then((documentSnapshot) => {
setCategoriesList(documentSnapshot.data().category);
setSelectedCategory(documentSnapshot.data().category[0].name);
setFields(documentSnapshot.data().category[0].fields);
fields.map((field) => {
refInputs.current.push("");
});
})
.catch((error) => {
console.log(error);
});
}, []);
const addInput = () => {
refInputs.current.push("");
setFields([
...fields,
{ name: "First", value: "", type: "string", encrypt: false },
]);
};
const removeInput = (i) => {
refInputs.current[i] = "";
setFields((fields) =>
fields.map((field, index) => {
if (index === i) {
return null;
}
return field;
})
);
};
const setInputValue = (index, value) => {
refInputs.current[index] = value;
};
const inputs = [];
fields.forEach((field, i) => {
if (field !== null) {
inputs.push(
<View
key={i}
>
<TextInput
onChangeText={(value) => setInputValue(i, value)}
value={refInputs.current[i]}
/>
<TouchableOpacity
onPress={() => removeInput(i)}
>
<Ionicons name="close" style={[tw``]} size={22} color="#ddd" />
</TouchableOpacity>
</View>
);
}
});
const addEntry = () => {
//
};
return (
<ScrollView style={styles.container}>
<Dropdown
data={categoriesList}
value={selectedCategory}
onChange={(item) => {
refInputs.current = [];
setSelectedCategory(item.name);
setFields(item.fields);
item.fields.map((field) => {
refInputs.current.push("");
});
}}
/>
<Input
onChangeText={setName}
value={name}
placeholder="Name"
/>
{inputs}
<Pressable onPress={addInput}>
<Text}>+ Add a new input</Text>
</Pressable>
<MainButton onPress={addEntry}>Add</MainButton>
</ScrollView>
);
}

Ant design Transform component extracting selected data

I need to extract selected/filtered data into the state. I tried everything with onChange and on select change but only I got is the ID of one specific item.
ex. extracted_data = [ '1','2','3'....]
But I need a complete Item with id, name, price, etc...
I am passing data as source data, and after selecting I want to send in the parent component because I need to send it on the server.
Code is below
import { Table, Transfer } from "antd";
import difference from "lodash/difference";
import React, { useState } from "react";
// Customize Table Transfer
const TableTransfer = ({ leftColumns, rightColumns, ...restProps }) => (
<Transfer {...restProps}>
{({
direction,
filteredItems,
onItemSelectAll,
onItemSelect,
selectedKeys: listSelectedKeys,
disabled: listDisabled,
}) => {
const columns = direction === "left" ? leftColumns : rightColumns;
const rowSelection = {
getCheckboxProps: (item) => ({
disabled: listDisabled || item.disabled,
}),
onSelectAll(selected, selectedRows) {
const treeSelectedKeys = selectedRows
.filter((item) => !item.disabled)
.map(({ key }) => key);
const diffKeys = selected
? difference(treeSelectedKeys, listSelectedKeys)
: difference(listSelectedKeys, treeSelectedKeys);
onItemSelectAll(diffKeys, selected);
},
onSelect({ key }, selected) {
onItemSelect(key, selected);
},
selectedRowKeys: listSelectedKeys,
};
return (
<Table
rowSelection={rowSelection}
columns={columns}
dataSource={filteredItems}
size="small"
style={{
pointerEvents: listDisabled ? "none" : undefined,
}}
onRow={({ key, disabled: itemDisabled }) => ({
onClick: () => {
if (itemDisabled || listDisabled) return;
onItemSelect(key, !listSelectedKeys.includes(key));
},
})}
/>
);
}}
</Transfer>
);
const leftTableColumns = [
{
dataIndex: "name",
title: "Name",
},
{
dataIndex: "price",
title: "Price (€)",
},
{
dataIndex: "discount",
title: "Discount (%)",
},
];
const rightTableColumns = [
{
dataIndex: "name",
title: "Name",
},
{
dataIndex: "price",
title: "Price",
},
];
const App = ({ data, func }) => {
const mockData = data.map((item) => ({
key: item.id.toString(),
name: item.name,
price: item.price,
discount: item.discount,
}));
const originTargetKeys = mockData.map((item) => item.key);
const [targetKeys, setTargetKeys] = useState(originTargetKeys);
const [selected, setSelected] = useState([]);
const onSelectChange = (e) => {
setSelected(e);
};
const onChange = (e) => {
setTargetKeys(e);
func(selected);
};
return (
<>
<TableTransfer
dataSource={mockData}
targetKeys={targetKeys}
disabled={false}
showSearch={true}
onChange={onChange}
onSelectChange={onSelectChange}
filterOption={(inputValue, item) =>
item.name.indexOf(inputValue) !== -1
}
leftColumns={leftTableColumns}
rightColumns={rightTableColumns}
/>
</>
);
};
export default App;

How to execute useState dynamically from strings in react hooks?

I have an object
const configs = [
{
label: 'Title',
name: 'Title',
value: titleToString,
field: SinglelineTextfield,
uniqueIdentifier: 0,
stateVar: 'criticalObjectTitle',
setStateVar: 'setCriticalObjectTitle',
},
{
name: 'type',
uniqueIdentifier: 1,
label: 'type',
value: typeToString,
field: SinglelineTextfield,
stateVar: 'criticalObjectType',
setStateVar: 'setCriticalObjectType',
},
{
name: 'Domain',
label: 'Domain',
value: domainToString,
field: SinglelineTextfield,
uniqueIdentifier: 2,
stateVar: 'criticalObjectDomainName',
setStateVar: 'setCriticalObjectDomainName',
}
]
I am retrieving the setState Variable wwwith the setFindVal in my onChange
const onChange = async (e) => {
const name = e.target.name || e.target.getAttribute('name')
const value = e.target.innertext ? e.target.innertext
: e.target.value
const setFindVal = configs.find(config => config.name === name).setStateVar
setFindVal(value)
console.log(setFindVal(value));
}
However, when I want to use setFindVal as a useState hook, it tells me that setFindVal is not defined..When I log setFindVal and its property type i get its a string, so I have created a useState hook outside of my function, however this still does not work. How do I convert a string into a useState function?
Error:
Uncaught (in promise) TypeError: setFindVal is not a function
Full code:
const editCriticalObjects = props => {
const query = new URLSearchParams(props.location.search)
const criticalObjectsId = query.get('id')
const loading = useContext(LoadingContext)
const user = useContext(UserContext)
const testing = useContext(TestingFrameworkContext)
const [editCriticalObjects, setEditCriticalObjects] = useState(null)
const [findval, setFindVal] = useState(null)
const [criticalObjectTitle, setCriticalObjectTitle] = useState(null)
const [criticalObjectDomainName, setCriticalObjectDomainName] = useState(null)
useEffect(() => {
async function onLoadCriticalObjects() {
loading.setLoading(true)
const results = await get(`get_critical_objects?id=${criticalObjectsId}`, user.user)
setEditCriticalObjects(results)
loading.setLoading(false)
}
onLoadCriticalObjects()
}, [])
const assetIdObject = editCriticalObjects && editCriticalObjects.filter(obj => {
if (obj.asset_id === criticalObjectsId )
return obj
})
console.log(assetIdObject);
const title = assetIdObject && assetIdObject.map(item => item.asset_id)
console.log(titleToString);
const titleToString = title && title.join(', ')
const domain = assetIdObject && assetIdObject.map(item => item.Domains.toString())
const domainToString = domain && domain.join(', ')
const type = assetIdObject && assetIdObject.map(item => item.type.toString())
const typeToString = type && type.join(', ')
const configs = [
{
label: 'Title',
name: 'Title',
value: titleToString,
field: SinglelineTextfield,
uniqueIdentifier: 0,
stateVar: 'criticalObjectTitle',
setStateVar: 'setCriticalObjectTitle',
},
{
name: 'type',
uniqueIdentifier: 1,
label: 'type',
value: typeToString,
field: SinglelineTextfield,
stateVar: 'criticalObjectType',
setStateVar: 'setCriticalObjectType',
},
{
name: 'Domain',
label: 'Domain',
value: domainToString,
field: SinglelineTextfield,
uniqueIdentifier: 2,
stateVar: 'criticalObjectDomainName',
setStateVar: 'setCriticalObjectDomainName',
}
]
const getObjectParams = {
asset_ids: criticalObjectTitle,
asset: true,
merge: true,
}
const onChange = async (e) => {
const name = e.target.name || e.target.getAttribute('name')
const value = e.target.innertext ? e.target.innertext
: e.target.value
const setFindVal = configs.find(config => config.name === name).setStateVar
setFindVal(value)
console.log(setFindVal(value));
}
const onClick = async () => {
loading.setLoading(true)
const results = await verifiedPost('post_critical_objects', testing.getObjectParams, user.user)
loading.setLoading(false)
console.log(getObjectParams);
}
return (!editCriticalObjects ? null :
<React.Fragment>
<PageWrapper title='Edit Critical Objects:'>
<div className='Main Card editCriticalObjectFormWrapper'>
{configs.map((config, k)=> {
const Field = config.field
return (
<React.Fragment key={config.name} >
<Field
style={{ marginBottom: '15px'}}
name={config.name}
placeholder={config.name}
value={config.stateVar}
initialValue={config.stateVar}
initialValues={config.stateVar}
uniqueIdentifier={k}
label={config.label}
onChange={onChange}
/>
</React.Fragment>
)
})}
<Button
className='Button Ghost Approve'
text='Submit'
onClick={onClick}
/>
</div>
</PageWrapper>
</React.Fragment>
)
}
export default editCriticalObjects
logging one value
new onchange:
const onChange = async (e) => {
const name = e.target.name || e.target.getAttribute('name')
const value = e.target.innertext ? e.target.innertext
: e.target.value
const setFindVal = configs.find(config => config.name === name).setStateVar;
setStateValues[setFindVal](value);
console.log(setFindVal, value);
}
The reason your getting it's not a function is because you are just using the value from the configs object which is a string.
You should assign the function as the value in config
const configs = [
{
...
setStateVar: setCriticalObjectTitle,
},
{
...
setStateVar: setCriticalObjectType,
},
{
...
setStateVar: setCriticalObjectDomainName,
}
];

How to make field validation?

How to make field validation?
I have an object with fields from which I generate a form, and when submitting, I need to check each field so that it is not empty, I do this, but it doesn’t work
My form:
const [volunteerData, setVolunteerData] = useState({
fullName: {
value: '',
type: "text",
placeholder: "Name",
label: "Name"
},
phone: {
value: '',
type: "text",
placeholder: "Phone number",
label: "Phone number",
mask: "+7(999) 999 99 99"
}
)}
Render form:
const onHandleRenderForm = () => {
return Object.keys(volunteerData).map((items, idx) => {
const control = volunteerData[items];
return (
<div key={idx} className="content-data-box">
<label>{control.label}</label>
<InputMask
type={control.type}
placeholder={control.placeholder}
mask={control.mask}
onChange={e => onHandleFormData(e, items)}
/>
</div>
)
})
};
onChange input:
const onHandleFormData = (e, items) => {
const before = {...volunteerData};
const after = {...before[items]}
after.value = e.target.value;
before[items] = after;
setVolunteerData(before);
};
onClick (submit button):
const onHandleErrorBoundary = () => {
Object.keys(volunteerData).map(items => {
const errorData = items.value === '';
console.log(errorData)
})
};
Change items.value === '' to volunteerData[items].value !== ""
const onHandleErrorBoundary = () => {
Object.keys(volunteerData).map(items => {
const errorData = volunteerData[items].value !== "";
return console.log(errorData);
});
};
you can check here codesandbox

Resources