object, Object instead of correct data from object VueJS - javascript

I pass the following props in my month component
props: {
actionEvents: this.selectedEvent && this.selectedEvent.calendar && this.selectedEvent.id || this.selectedEvent
}
In my ChangeCalendar component I'm trying to update the api by doing the following:
? this.$api.calendar.update(
this.actionEvents && this.actionEvents.id && this.actionEvents.calendar || this.actionEvents,
data
I need both Id and calendar for the route to update but the output I get is:
"/calendars/f2User-51-5594439/events/[object Object]". I would expect object Object to return the calendar value (which is a string and is something like: f2User-51-actions).
Does anyone know what I'm doing wrong here? I dont understand why Id does return the expected value but calendar doesn't
When I look into the data and props of my components:

Related

[Vue warn]: Invalid prop: type check failed for prop "....". Expected String, returned function()

I have been getting this error today. I am using VUEX for the first time, and I am trying to use a Getter to find an element in an array. I assume that the problem must be in the second parameter (title) that I am passing in the first code snippet, or in the way that I call the getErrorByMbId function.
What I am doing in the store registering the Getter:
[GETTERS.GET_ERROR_BY_MB_ID]: state => title => {
return state.submitErrors.find(e => e.meta.name === title)?.content
.titleOfError;
}
Introducing the getter in the component with mapGetters:
getErrorByMbId: PRODUCT_GETTERS.GET_ERROR_BY_MB_ID
Then I call the getter here in a computed. The title parameter accepts a string, that's why I am passing 'Number'. Number should be the title of the error.
return this.getErrorByMbId('Number');
If I donnot use Vuex, and just have a function in the computed, my code works fine. But I want to use Vuex isntead. Example:
numError() {
return this.errors.find(
e => e.meta.name === 'Number'
)?.content.titleOfError;
}
These are the errors in the console:
How it appears to the UI as an error message. Looks like it stringifies the function:
Update: Accidentally registered the mapGetters in methods instead of computed, that's why it did not work.
Your function parameters seem to be the wrong way around. In your first snippet you are returning a function that takes a parameter state and returns a function that takes a parameter title, when you want to return a state selector (that is, a function that takes state as a parameter).
Try this, just switching the names of the parameters:
[GETTERS.GET_ERROR_BY_MB_ID]: title => state => {
return state.submitErrors.find(e => e.meta.name === title)?.content
.titleOfError;
}

Why does this hook call return undefined when I simply change the variable name?

I'm running an API call via redux - in the tutorial, I am following, they use the variable name "sales" to store the data. Following along, I kept getting undefined, and after some troubleshooting, it appears that the only way for me to get any data out of this API call is to save the result in a variable named exactly "data".
// Correctly retrieves and logs the data
const { data, isFetching } = useGetSalesQuery();
console.log(data);
// Returns "undefined" every time
const { anythingElse, isFetching } = useGetSalesQuery();
console.log(anythingElse);
data is not defined anywhere else within this component. So what's going on here? Was Redux updated to force us to always use the name "data"? This is doing my head in.
useGetSalesQuery returns an object that has data and isFetching. Attempting to access an arbitrary field from that object will get you undefined. What's going on in this component is that you are defining a variable data and assign it the value from the field data that is returned from useGetSalesQuery
See javascript's destructuring assignment

How to fetch Data before Render ReactJS

so I have this custom hook which returns an array of Objects from database, before it gets data, the value of returned value is undefined. getDataByID(100).doc?.items - This returns the items from database as an array. How can I make sure that the returned Value is not undefined and then mount the component in functional components?
Try to fetch this data in parent component, and when you received the data then only mount required component as child component and pass those data as props.
{
(dataFromAPI !== undefined) ? <ChildComponent data={dataFromAPI} /> : undefined
}
In this way when you have dataFromAPI then only your child component will be mounted.
Mujibur Rehman Ansari's answer can furthur modified as
{ dataFromAPI && <ChildComponent data={dataFromAPI} /> }

How to get value from array of objects?

I have an react app, and using redux and props to get array of objects into my component, and i am getting them. But i can't access particular property inside of one of objects that are in that array.
With this:
console.log(this.props.users)
I get listed array with all objects inside it. But when i need to access particular object or property of that object, for example:
console.log(this.props.users[0])
console.log(this.props.users[0].name)
I am getting error:
Cannot read property '0' of undefined
But when I iterate through array with map() method i have access to it, it works. Why can't i access it normally?
You are trying to access properties of this.props.users before it has loaded. Your component renders without waiting for your data to fetch. When you console.log(this.props.users) you say that you get an array, but above that, it probably logs undefined at least once when the component renders before this.props.users has loaded.
You have a couple of options. You can either do this at the very top of your render method to prevent the rest of the code in the method from executing:
if (!this.props.users) return null;
Once the data is fetched and props change, the render method will be called again.
The other option is to declare a default value, of an empty array for users in your reducer.
Might be when you are executing that line this.props.users is undefined. Check the flow where you have added console.log(this.props.users[0])
const App = () => {
const example = () => {
const data =[{id:1 ,name: "Users1", description: "desc1"},
{id:2 ,name: "Users2", description: "desc2"}];
return (
<div>
{data.map(function(cValue, idx){
console.log("currentValue.id:",cValue.id);
console.log("currentValue.name:",cValue.name);
console.log("currentValue.description:",cValue.description);
return (<li key={idx}>name = {cValue.name} description = {cValue.description}</li>)
})}
</div>
);
}
return(
<p style = {{color:'white'}}>
{example()}
</p>
);
}
export default App;

An array with objects, within an object is undefined

I have an array that contains objects, inside an object.
I can console.log the first object and the array, but when i try to access the objects within the array or use the map-function on the array i get an error that says "Can't read property of undefined".
I have thoroughly searched SO and other sites for similar problems and found some but no answers seems to work for me.
The object looks like this:
{
answers: [{…}],
createdAt: "2019-01-23T10:50:06.513Z",
nested: {kebab: "jjjj", sås: 2, sallad: "kkk"},
text: "weaxcc",
/* etc... */
}
And i can access it using: this.state.data
I want to access objects inside the answers-array like:
this.state.data.answers[0].text
or even :
this.state.data.answers.map().....
But that gives me 'Cannot read property '0' of undefined. The answers-array is not empty.
Any help is appreciated!
EDIT
This is how the objects ends up in my state.
getQuestionFromDb = () => {
axios.get(`http://localhost:3000/questions/${this.state.id}`)
.then(res => this.setState({
data: res.data
}));
};
This function is called in the ComponentDidMount()-method.
Here is my render function (the console.log is causing the error):
render() {
return (
<div className="main-content">
<h2>{this.state.data.text} </h2>
{console.log(this.state.data.answers[0].text)}
<p>Introducing <strong>{this.state.id}</strong>, a teacher who loves teaching courses about <strong>{this.state.id}</strong>!</p>
<input
type="text"
onChange={e => this.setState({ message: e.target.value })}>
</input>
<button onClick={() => {this.handleAnswerPost(this.state.message)}}>Answer</button>
</div>
);
}
}
componentDidMount is getting called when your component becomes part of the DOM but the call you do to populate your state is async due to XHR, which may take 100-300ms more to get the data in your component, so this.state.data.answers won't be available in the initial render() cycle.
since you mentioned using a loop, I suggest setting an initial state shape like
this.state = {
data: {
answers: []
}
}
your initial render won't have anything to loop but as soon as it resolves the data and sets the new state, it will render correctly.
alternatively you can
return this.state.data.answers.length ? loopItemsHere : <div>Loading..</div>
obviously, loopItemsHere can be anything you write to show the answers.
This might not be working when data doesnt contain answers[] at the very first mount for a component.
You may wanna check for your array's existance as following:
const { data } = this.state;
data.hasOwnProperty('answers') && console.log(data.answers[0]);
The reason we can't access object key in Javascript, usually it is because the variable/value is not the type of Object. Please ensure that this.state.data type is Object. You can try to console.log( typeof this.state.data ). We should expect that it is output object. If the type is string, you should parse it first with JSON.parse().
There may be a number of reasons that could cause the data object not to be shown:
The object was not in state at the time of it being called. This may be caused by an async operator not loading in the data. E.g. if you are requesting for the object from the database, chances are that at the time of making a call to retrieve the data (this.state.data), the response had not been given.
The object may not have been parsed into string. Try running console.log(typeof this.state.data). If the output is string, then you may have to parse it. If the output is undefined, then point one is valid

Categories

Resources