i want to pass input value to function in react but i cant send value here is my code
{users.map((user) => (
<TableCell align='right'>
<TextField
select
sx={{ minWidth: 120 }}
value={user.status !== null ? user.status : 'waiting'}
onChange={() => changeUserStatus(user.id, user.status, this)}
>
<MenuItem
value={"approved"}
>
Approve
</MenuItem>
<MenuItem
value={"rejected"}
>
Reject
</MenuItem>
<MenuItem
value={"waiting"}
>
Waiting
</MenuItem>
</TextField>
</TableCell>
);
))}
And function
const changeUserStatus = async (userId, oldStatus) => {
let newStatus;
// i need new status coming from input value
if(oldStatus === 'approved') {
newStatus = 'rejected';
} else {
newStatus = 'approved';
}
const request = await fetch(`xx.com/api`, {
method: 'POST',
headers : { 'Content-Type': 'application/json' },
body: JSON.stringify({ user_id: userId.toString(), status: newStatus}),
}).then(response => {
updateUsers()
})
.catch(err => console.error("Change Status Error", err))
}
i know a way to do it but, Im using map function to read data
Related
In my project, I'm using ReactJS as a frontend and Flask for Backend.
Here's a code I wrote to Get a case's details in the from of JSON and also convert it to Pretty JSON.
I now require a download button with which I can take the JSON input and download it as JSON, PDF and XML.
Here's the code-
CaseTree.js
<Grid item xs={12} md={10} className={classes.rightUpperPart}>
{/* Render CaseTree in Pretty Json format */}
{
(caseReducer.isLoading || !caseReducer.caseTree ||fileReducer.isLoading || !fileReducer.file || !fileReducer.fileType) ? (
<JsonPretty data={caseReducer.caseTree}/>
) : (fileReducer.fileType === 'report' || fileReducer.fileType === 'txt') ? (
<ShowTXT data={fileReducer.file} className={classes.rightPart}/>
) : (fileReducer.fileType === 'tsv') ? (
<ShowTSV data={fileReducer.file} className={classes.rightPart}/>) : (
<pre className={classes.preStyle}>{fileReducer.file}</pre>
)
}
</Grid>
**ADD DOWNLOAD BUTTON HERE**
JSON Pretty File
import React from 'react';
import { makeStyles } from '#material-ui/core/styles';
import {
Box,
Typography
} from '#material-ui/core';
import { useSelector } from 'react-redux';
// custom styles
const useStyles = makeStyles((theme) =>({
root: {
backgroundColor: '#1f4662',
color: '#fff',
fontSize: '12px',
overflow: 'auto',
padding: theme.spacing(4),
height: theme.spacing(55),
},
headerStyle: {
backgroundColor: '193549',
fontFamily: 'monospace',
color: '#ffc600',
},
preStyle: {
display: 'block',
padding: '10px 3px',
margin: '0',
color: '#fff'
}
}))
function JsonPretty({data}) {
// invoke custom styles
const classes = useStyles()
// get case Reducer
const caseReducer = useSelector(state => state.case)
// default json data
const defaultData = {
"processing": ( caseReducer.isLoading ) ? "Wait Processing..." : "Done",
"success": false,
"message": ( caseReducer.error ) ? caseReducer.error : "Please Provide a Case Name.",
}
return (
<Box component="div" className={classes.root}>
<Typography className={classes.headerStyle}>
Pretty Json Format
</Typography>
{
(data) ? (
<pre className={classes.preStyle}>
{JSON.stringify(data, null, 4)}
</pre>
) : (
<pre className={classes.preStyle}>
{JSON.stringify(defaultData, null, 4)}
</pre>
)
}
</Box>
)
}
export default JsonPretty
LoadCaseTree def
export const loadCaseTree = (case_name) => (dispatch) => {
//// dispatch laod case
dispatch({
type: LOAD_CASE_TREE
})
//// Create request data body
const data = {
case_name: case_name
}
//// Get token from localstorage
const token = localStorage.getItem('openmf_token')
//// add headers
const config = {
headers: {
'Content-Type': 'application/json'
}
}
//// If token available add to headers
if (token) {
config.headers.Authorization = `Bearer ${token}`
} else {
dispatch({ type: LOAD_CASE_TREE_FAILED })
dispatch(setAlert('Please Log In.'))
return
}
//// Send request to server
axios.post('/case/case-tree', data, config)
.then((res) => {
const case_tree_json = JSON.parse(res.data.tree)
dispatch({
type: LOAD_CASE_TREE_SUCCESSFULL,
payload: {
tree: case_tree_json,
case: res.data.case
}
})
dispatch(setAlert(res.data.message, 'success'))
})
.catch((err) => {
const res = err.response
//// check err status code
if(res && (res.status === 404 || res.status === 422 || res.status === 500)){
dispatch({
type: LOAD_CASE_TREE_FAILED,
payload: {
error: res.data.message
}
})
dispatch(setAlert(res.data.message))
return
}
//// FOr unknown reason
dispatch({
type: LOAD_CASE_TREE_FAILED,
payload: {
error: 'Something went wrong.'
}
})
//// dispatch alert
dispatch(setAlert('Something went wrong.'))
})
}
Please let me know if I've missed out on any code snippet or information.
code:-
useEffect(() => {
setPlayer();
window.addEventListener("keydown", handleKeyDown);
return function cleanup() {
window.removeEventListener("keydown", handleKeyDown);
};
}, [props])
const handleKeyDown = (event, ID) => {
if (event.key === "Delete") {
//alert(name);
axios({
method: 'post',
url: `${API_ENDPOINT}/api/setCue?Idx=${ID}&RDL=${props.val}`,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-control-allow-origin': '*'
},
auth: {
username: 'admin',
password: 'password'
},
}).then(response => {
console.log("Delete Inside Axios");
}).catch(error => {
console.log("Error In Post Data", error);
});
console.log("Delete Key Press", ID, props.val);
}
}
<tbody>
{
PlaylistData && PlaylistData.map((playdata) => {
return (
<tr key={playdata.idx} tabIndex={playdata.idx} className="border_bottom"
KeyDown={(e) => handleKeyDown(e, playdata.idx)} onLoad={() => active(playdata.idx)}
>
<td style={{ color: "white", width: "200px" }}>
<img src={`data:image/jpeg;base64,${base64}`} alt="Clip Thumbnail" width="50%" />
</td>
when I click the delete button it does not send the table index but when I remove the window.addEventListener("keydown", handleKeyDown); its sending the id number but not the props values
I want both id and props values to print in the console.
How can I fix that?
please help.
You can get the value of target using event.code == "Delete". So replace event.key by event.code
You can see the example below to see how it works i.e. go to input and then press any key to see the key entered.
const input = document.querySelector('input');
const log = document.getElementById('log');
input.onkeydown = logKey;
function logKey(e) {
log.textContent += ` ${e.code}, `;
}
<input>
<h3 id="log"></h3>
code:-
<div>
{ChannelName.map((val, index) => {
return (
<div className="TextLink" key={index}>
<NavLink to={`/`}
onClick={(e) => myClick(val, index)} >
<button className='notActive buttonLeft'
onClick={() => { handleOnClick(index); handleClick(val, index); setPage("Table") }} // pass the index
className={activeIndex === index ? "active" : "notActive"}>
{val}
</button>
</NavLink>
</div>
)
})
}
</div>
{page === "Table" ? <Table val={getname}/> : null}
2 component table url:-
const userId = props.val;
useEffect(() => {
setInterval(() => {
getData();
}, 300);
}, [userId]);
const getData = () => {
console.log(`inside${userId}`);
axios.get(`${API_ENDPOINT}/api/getPlaylist?RDL=${menuId}`, {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-control-allow-origin': '*'
},
auth: {
username: 'admin',
password: 'password'
}
}).then(response => {
setIsLoading(true);
setPlaylistData(response.data.Clips);
setChannel([(response.data.Players)]);
// console.log("table", response.data.Clips);
//console.log([...Object.values(response.data.Players).flat()]);
}).catch(error => {
console.log("Error In GET Data", error);
});
I want when I click the menu then menu URL parameters goes to the menuId and then the api show according then
Right now i am props the the onclick name and when i click on the second button its show me new api and 1 menu api
how can i fix that?
This is just your common formic form with error and a sumbmit method ,for updationg fields. But how do you save your previous answer (not new one when update) and the name of your textfield to another variable.When I press submit I want to save the name of the textfield and the old answer
export default function Index ({ setFile, setMessageDisplay, ...props }) {
let currentUser = AuthService.getCurrentUser();
const [ notesId, setNotesId ] = useState();
const [ releaseNotes, setReleaseNotes ] = useState({});
const formRef = useRef();
//Get todays date
var today = new Date(),
date = today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate();
let url = `releaseNotes/all`;
function fetchData () {
Api(url, 'Get').then((data) => {
setReleaseNotes(data[0]);
setNotesId(data[0].id)
});
}
//Get data on start
useEffect(
() => {
fetchData();
},
[ url ]
);
Updating and saving data
//Insert data /Update data
async function submitForm (values) {
// routine to send the request to the server
const formData = new FormData();
var postData = values;
console.log(postData);
formData.append(
'releaseNotes',
new Blob([ JSON.stringify(postData) ], {
type: 'application/json'
})
);
//Send request
return Api(`releaseNotes/updateReleaseNotes`, 'Post', formData);
}
return (
<div>
Just Formik containing one field
<Formik
innerRef={formRef}
enableReinitialize={true}
initialValues={{
id: notesId,
notes: releaseNotes.notes || '',
lastUpdated: moment(date) || ''
}}
validationSchema={Yup.object().shape({
verified: Yup.bool()
})}
onSubmit={async (values, { resetForm, setErrors, setStatus, setSubmitting }) => {
try {
//Call submitForm function
submitForm(values).then(() => {
});
} catch (error) {
setStatus({ success: false });
setErrors({ submit: error.message });
setSubmitting(false);
}
}}>
{({
errors,
handleBlur,
handleChange,
handleSubmit,
isSubmitting,
setFieldTouched,
setFieldValue,
touched,
values
}) => (
<form onSubmit={handleSubmit} {...props}>
<Card>
<CardContent>
<Box mt={2}>
<TextField
fullWidth
multiline
label='Notes'
name='notes'
onChange={handleChange}
value={values.notes}
variant='outlined'
/>
</Box>
<Box mt={3} style={{ display: 'flex', float: 'right' }}>
<Button variant='contained' color='secondary' type='submit' disabled={isSubmitting}>
Save Changes to ReleaseNotes
</Button>
</Box>
</CardContent>
</Card>
</form>
)}
</Formik>
This is the function I want to submit as well, something like this in mind
async function updateActivity (formName,oldValue) {
const activityData={
field:values.name,
function:"Change",
category:"Admin Change",
userWhoMadeChange:currentUser.name,
userChangeID:values.id,
name:formName,
oldValue:oldValue
}
const formData = new FormData();
// routine to send the request to the server
formData.append(
'activityLog',
new Blob([ JSON.stringify(activityData) ], {
type: 'application/json'
})
);
//Send request
return Api(`activityLog/updateActivityLog`, 'Post', formData);
}
I get this data as a response
[
{
"breakfast": [
"3x Eggs",
"2x Bread",
"Cup of Milk",
],
"lunch": [
"1/4 Chicken breast",
],
"dinner": [
"1x Apple",
],
"snack": [],
"_id": "5dd5224d76cf581424e1bb84",
},
]
I want to display them like this
here is my code
async componentDidMount(){
const breakfast = [];
const headers = {
'Authorization': GLOBAL.jwt
};
await axios({
method: 'GET',
url: 'http://192.168.1.101:4040/users/dietData',
headers: headers,
}).then((response) => {
response.data.forEach(item => {
breakfast.push(item.breakfast)
breakfast.forEach(item => { console.log(item)})
})
this.setState({
breakfast: breakfast,
dataSource: response.data,
});
}).catch((error) => {
Toast.show({
text: "[Error] Network Error, Please try again later",
buttonText: "Okay",
type: "danger",
duration: 3000
})
});
}
weightData = ({item}) => {
item.breakfast.forEach(
item => {
console.log(item)
return (
<ListItem>
<Text>{item}</Text>
<CheckBox style={{ marginLeft:210, alignSelf: 'flex-end'}} checked={false} color="#FC7B04" />
</ListItem>
)
}
);
}
render() {
return (
<View style={styles.dietCard}>
<FlatList
inverted
data={this.state.dataSource}
renderItem={ this.weightData }
keyExtractor={(item, index) => index}
/>
</View>
);
}
and here is the result of the console.log(item)
3x Eggs
2x Bread
Cup of Milk
but the problem is nothing is showing on the screen I tried to re-irritate the items so 3 items are shown but with no luck? any ideas?
and if I removed the foreach loop i get the 3 elements of the array in the same listitem not i want them in seperate list items
Use SectionList like below which full-fill your requirement.
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => <Item title={item} />}
renderSectionHeader={({ section: { title } }) => (
// your renderUI view code is here..
)}
/>
follow below link for more details.
https://facebook.github.io/react-native/docs/sectionlist