Passing props to a state to use in a class component - javascript

Will preface that I have about 4 weeks of coding experience and so apologies in advance if I'm missing something obvious.
I'm trying to pass an array of objects from Profile.js to Calendar.js, with Calendar.js currently ultimately being returned again in Profile.js. The idea's that a user would be able to set a schedule and be able to see the same schedule when they go back to the profile page. I was trying to get this to work by having the saved array of objects be displayed upon rendering the Calendar.js, but right now it basically resets itself every time the user goes back to the page.
Two issues I'm guessing are relevant here:
Initializing this.state to this.props.calendar isn't working (seems like this.props.calendar returns empty during initialization) but when I log this.props.calendar in the handleChange or render() it does show up correctly.
I believe handleChange runs whenever the page is clicked and so was thinking there might need to be some way for Calendar.js to display the old saved array of objects instead of an empty array (in case no schedule is selected at the time of click). Was trying to implement some kind of conditional operator here but handleChange currently stops working if it is called while a new empty schedule's selected (so if the user happens to click on the page before selecting a schedule).
This came out to be a bit longer than I expected, but any help would be greatly appreciated!
Calendar.js:
export default class Calendar extends React.Component {
constructor(props) {
super(props);
this.state = {
schedule: this.props.calendar
};
}
handleChange = newSchedule => {
this.setState({ schedule: newSchedule.length !==0 ? newSchedule : this.props.calendar });
this.props.handleSubmitCalendar(newSchedule); // call API function to save current selected schedule to a database
}
render() {
return (
<ScheduleSelector
selection={this.state.schedule}
...code...
/>
)
}
}
Profile.js:
import Calendar from "../components/Calendar";
export default function Profile() {
const [calendar, setCalendar] = useState([]);
useEffect(() => {
async function onLoad() {
try {
const profileCalendar = await loadCalendar();
setCalendar(profileCalendar);
} catch (e) {
onError(e);
}
}
onLoad();
}, []);
async function handleSubmitCalendar(calendar) {
setIsLoading(true);
try {
updateCalendar(calendar);
setIsLoading(false);
} catch (e) {
onError(e);
setIsLoading(false);
}
}
function loadCalendar() {
return API.get("notes", "/calendar");
}
function updateCalendar(calendar) {
return API.put("notes", "/calendar", {
body: {calendar}
});
}
return (
<div className="Calendar">
<Calendar calendar={calendar} handleSubmitCalendar={handleSubmitCalendar}/>
</div>
);
}

Welcome! You should really read the React documentation and go through the examples. Everything you need to known to answer this question is in there and going through it all will make you a more competent developer and save you a lot of headaches. Available here. If you still don't understand once you've gone through the docs, ask again here and I will help you.

Related

Stop requesting when changing the route in ReactJs

I make an request in react js and i get data using useSelector. So in useEffect i show the message from backend after the request.
useEffect(() => {
if (selector.response ? .message) {
console.log(selector);
message.success(selector.response?.message, 2);
setLoading(false);
}
console.log('render');
}, [selector.response]);
The code works fine, but appears an issue when i change the page(route). Clicking on another menu item i go to another page and when i come back, the useEffect is triggered again and user again sees the message from message.success(selector.response?.message, 2);. Question: How to stop showing the message each time after i come back to my route and to show the message just one time?
You have to use User Effects with Cleanup
You need to clean up the effects from the previous render or actions. Otherwise it will hold the previous state
You will find more details in official tutorial
userEffect Cleanup Process
Update Answer
import React, {useState, useEffect} from "react";
export default function App() {
const [count, setCount] = useState(0);
useEffect(() => {
function handleChange(val) {
setCount(val)
}
window.addEventListener('load', handleChange(1))
return () =>{
handleChange(0);
console.log(count)
};
})
return (
<div className="App">
{count}
</div>
);
}
Here I take a count variable and setCount methods to set the count variable
Inside useEffect I create a function which will be responsible for setting up count value
Then I create an addEventListner when the page will load it will set the count value to 1
Then I call an anonymous function for clean up things which will remove the previously set value to 0
After that I set a console to just check if its sets the value
So when user come back to your page again initially it will find the default value then set the dynamic value.
You can make it more efficient way. I just give you an example
Below I share a link which will help you to handle api response
How to call api and cleanup response using react usereffect hooks
It seems like in your case your component unmounts upon page change and remounts when the user comes back. When the componet remounts, the useEffect always fires. That's simply how it works.
Answering your question, this is a simple thing you can do for your case.
// this will create a function that will return true only once
const createShouldShowSuccessMessage = () => {
let hasShownMessage = false;
()=> {
if(hasShownMessage) {
return false;
} else {
hasShownMessage = true;
return true;
}
}
};
const shouldShowSuccessMessage = createShouldShowSuccessMessage();
const SomeComponent = () => {
useEffect(() => {
if(shouldShowSuccessMessage()) {
message.success(selector.response?.message, 2);
}
setLoading(false);
}, [selector.response]);
}
I would advise you got with a better setup that performing your side effects inside your components but I hope my answer helps you till you get there

React re-render conditional on state change without changing the conditional

I've got a conditional that displays an editor while a certain prop remains true. The thing is, the data with which that editor is rendered with should change every time I select another object with which to populate that editor.
However, because the prop responsible for the conditional rendering doesn't change, even though the data with which the editor is rendered does, it refuses to re-render on state change.
I'm not particularly good at React, so, hopefully someone can explain how I can get around this little hiccup.
Conditional render
{this.state.showEditor ? (<BlockEditor routine={this.state.editorObject} />) : null}
Method that is being called.
handleShowEditor = routine => {
this.setState({ showEditor: true });
this.setState({ editorObject: routine });
};
The editor component
export default class BlockEditor extends React.Component {
constructor(props) {
super(props);
this.state = {
routine: this.props.routine
};
}
render() {
return (
<div>
<Editor
autofocus
holderId="editorjs-container"
onChange={data => this.handleSave(data)}
customTools={{}}
onReady={() => console.log("Start!")}
data={this.props.routine.description}
instanceRef={instance => (this.editorInstance = instance)}
/>
</div>
);
}
}
Is there a reason for setting state separately? Why not
handleShowEditor = routine => {
this.setState({
showEditor: true,
editorObject: routine
});
};
Keep in mind that setState is asynchronous and your implementation could lead to such weird behaviour.
If you are still looking for an answer i have faced the same problem working with the same [Editor.JS][1] :).
This worked for me with functional component:
// on change fires when component re-intialize
onChange={async (e) => {
const newData = await e.saver.save();
setEditorData((prevData) => {
console.log(prevData.blocks);
console.log(newData.blocks);
if (
JSON.stringify(prevData.blocks) === JSON.stringify(newData.blocks)
) {
console.log("no data changed");
return prevData;
} else {
console.log("data changed");
return newData;
}
});
}}
// setting true to re-render when currentPage data change
enableReInitialize={true}
Here we are just checking if data changes assign it to editorData component state and perform re-render else assign prevData as it is which will not cause re-render.
Hope it helps.
Edit:
i am comparing editor data blocks change which is array.
of course you need to perform comparison of blocks more deeply than what i am doing, you can use lodash for example.
[1]: https://github.com/editor-js/awesome-editorjs
As setState is asynchronous you can make another call in its callback.
Try like this
handleShowEditor = routine => {
this.setState({
showEditor: true
}, () =>{
this.setState({
editorObject: routine
)}
});
};

React : How to avoid multiple function call

I am working on small react project, actually I have some problem regarding to function call. I am updating the value of URL and invoke the method through button click to display updated values but whenever I click the button first it give me old values when I click again it give me updated values. Could someone please help me how to avoid old values on first click, I want to show updated values on first click not on second click. I am new to ReactJS , Could someone please help me how to fix this problem?
Full Component Code
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
Item: 5,
skip: 0
}
this.handleClick = this.handleClick.bind(this);
}
urlParams() {
return `http://localhost:3001/meetups?filter[limit]=${(this.state.Item)}&&filter[skip]=${this.state.skip}`
}
handleClick() {
this.setState({skip: this.state.skip + 1})
}
render() {
return (
<div>
<a href={this.urlParams()}>Example link</a>
<pre>{this.urlParams()}</pre>
<button onClick={this.handleClick}>Change link</button>
</div>
)
}
}
ReactDOM.render(<Example/>, document.querySelector('div#my-example' ))
State is not updating at time when urlParams is being called. As #jolly told you setState is Asynch function so it's better to use it in a callback or you may simply pass your sortedData type as in argument in getSortedType function instead of updating state. Also, ReactJS community suggests or the best practice is to use state only if props are needed to be updated.
In case, if you dont feel comfortable with CB. you may use setTimeOut which I think is a bad practice but it would solve your problem. your code would be like:
getSortedData=()=>{
this.setState({sortedData:'name desc'});
setTimeout(() => {
this.getData();
}, 200);
}
There's quite lots of code e no working example, so I may be wrong, but I think the problem is in getSortedData(): in that function, you call setState() and right after you call getData() which will perform a fetch, which uses ulrParams() function, which uses property this.state.sortedData.
The problem in this is that setState() is async, so it's not sure that, when urlParams() uses this.state.sortedData, the property is updated (actually, we are sure it's not updated).
Try to rewrite getSortedData() as follow:
getSortedData =() => {
this.setState({sortedData:'name desc'}, () => {
this.getData();
})
}
What I'm doing here is passing a callback to setState(): doing this way, getData() will be called AFTER you've updated the state.
Regarding the question you asked in the comment, if you want to toggle the order, you can add a property order in the state of the Component, assigning to it a default value 'name desc'.
Then, you change getSortedData as follow:
getSortedData =() => {
let newSort = 'name asc';
if (this.state.sorteData === newSort) 'name desc';
this.setState({sortedData: newSort}, () => {
this.getData();
})
}

delete not working in ternary in setState

So I have been struggling with getting this section of the application working 100% as can be seen with these related questions:
Method renders correctly when triggered one at a time, but not using _.map in React-Redux container
Object passed into Redux store is not reflecting all key/values after mapStateToProps
So the setup is this... a bunch of buttons are dynamically generated based on the number of data "cuts" for a specific item (basically different ways of looking at the data like geography, business segment, etc.). The user can select one button at a time, click a Select All. This will retrieve the data related to the cut from the server and generate a table below the buttons.
One-at-a-time selections is working, select all is working, clear all is working. However, what I am trying to setup now is if the person clicks the same button again, it toggles that data point off.
This is where I was left after one of my previous questions:
onCutSelect(cut) {
this.setState(
({cuts: prevCuts}) => ({cuts: {...prevCuts, [cut]: cut}}),
() => this.props.bqResults(this.state.cuts)
);
}
Works fine for one at a time selections and the Select All (this function is called via a map from a different function).
Modified to this, which I was hoping would toggle the data point off:
onCutSelect(cut) {
this.setState(
({cuts: prevCuts}) => (
this.state.cuts.hasOwnProperty(cut)
?
delete this.state.cuts[cut]
:
{cuts: {...prevCuts, [cut]: cut}}),
() => this.props.bqResults(this.state.cuts)
);
What I would think should be happening, is checks if the key is there and if it is to delete it which will toggle the button off. And it does, it changes the button status to unselected.
However, what I would think should also happen, is since this.state.cuts is being modified, it will send the new this.state to the this.props.bqResults action. While the button is toggling off, it still shows the data related to the cut, so that store is not being updated for whatever reason. How should I be handling this?
Here is the remainder of the related code:
// results.js actions
export function bqResults(results) {
console.log(results); // shows all of the selected cuts here
return function(dispatch) {
dispatch({
type: FILTER_RESULTS,
payload: results
})
}
}
// results.js reducer
import {
FILTER_RESULTS
} from '../actions/results';
export default function(state = {}, action) {
switch(action.type) {
case FILTER_RESULTS:
console.log(action.payload); //prints out all the cuts
return {
...state,
filter_results: action.payload
}
default:
return state;
}
return state;
}
const rootReducer = combineReducers({
results: resultsReducer,
});
export default rootReducer;
onCutSelect(cut) {
this.setState(
({cuts: prevCuts}) => {
if (cuts.hasOwnProperty(cut)) {
const newCut = {...this.state.cuts}
delete newCut[cut]
return newCut
} else {
return {cuts: {...prevCuts, [cut]: cut}}
}
},
() => this.props.bqResults(this.state.cuts)
);
}
A few things. First, don't mutate state directly like that. Using delete removes the index number of the existing this.state.cuts. Perform this operation in a way that creates a completely new array when assigning your new value. I use the spread operator for this.
Also, when you return a delete operation, it's not returning what the array is after using delete. It returns delete's return value, which in this case is a boolean.
function delIdx(arr, idx) {
return delete arr[idx]
}
console.log(delIdx([1,3,4], 3))

Accessing data from Axios GET request

I'm having trouble accessing data from an Axios GET request. I'd like to be able to iterate through all of the data I get and create a table that displays the username, avatar, and score for each user. The only way I'm able to currently render a single username is with the following code:
this.setState({name: res.data[0].username});
But the above code only gives me access to the first object in the URL I use in the GET request. If I use this code:
this.setState({name: JSON.stringify(res.data)});
I'm able to render the entire object as a string. So that makes me think I need to update my render method, but I'm not sure how.
What steps should I take so that I can map over the state that I'm setting and render each user's data in a table or list?
class LeaderBoard extends React.Component {
constructor(props) {
super(props)
this.state = {
name: []
}
}
componentDidMount(){
axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(res =>
{
this.setState({name: res.data[0].username});
});
}
render () {
return (
<div>
<h1>{this.state.name}</h1>
</div>
)
}
}
ReactDOM.render(
<LeaderBoard/>, document.getElementById("app"));
You're on the right track, you're just missing a few key pieces.
Step 1: Add the entire array to your state
I'm not sure of the exact structure of your data, but you likely want to do this
componentDidMount(){
axios.get('https://fcctop100.herokuapp.com/api/fccusers/top/recent').then(res =>
{
this.setState({data: res.data});
});
}
Now you have all the data you want to work with in your state, ready to be iterated over.
Step 2: Use .map() to create the JSX elements you want
This code here:
render () {
return (
<div>
<h1>{this.state.name}</h1>
</div>
)
}
}
The big fault here is that it will only ever render one thing, because, well, that's all there is. What you want to do is .map() through and create a bunch of names from your data, right?
That would look more like this.
render () {
const namesToRender = this.state.data.map(val => {
return (
<h1>val.username</h1>
)
})
return (
<div>
{namesToRender}
</div>
)
}
}
All this is saying is "Go through that data and give me the name of each person and wrap it in some <h1> tags and spit that out".

Categories

Resources