Reputation: 1714
I have a react app with several API calls. I have a component and inside the component, I have a Class and a function outside the class. This component is a child one and receive some props from its parent. My API call is going in the outside function which is getSuggestionValue and that API call need a prop (jobId) coming from the parent class. The problem is I'm having the error
Cannot read property 'projectdata' of undefined
function getSuggestionValue(suggestion) {
const job_id = this.props.projectdata.jobId;
const user_id = suggestion.id;
API.post('job/assign_user', { job_id, user_id })
.then(({ data }) => {
console.log("success!", data)
})
.catch((err) => {
console.log("AXIOS ERROR: ", err);
})
return suggestion.label;
}
class ProjectModal extends Component {
constructor(props) {
super(props);
this.state = {
status: null
};
}
render() {
const autosuggestProps = {
getSuggestionValue
};
return(
<div>{this.props.projectdata.jobId}
<Autosuggest
{...autosuggestProps}
//other props
/>
</div>
//other function calls
)
}
}
I know that the problems is here
const job_id = this.props.projectdata.jobId;
in the getSuggestionValue function, but have no idea how to put the jobId to the API call. How can I do this?
Upvotes: 0
Views: 1497
Reputation: 5472
You can wrap your function:
const getSuggestionValue = (props) => (suggestion) => {
const job_id = props.projectdata.jobId;
const user_id = suggestion.id;
...
const autosuggestProps = {
getSuggestionValue: getSuggestionValue(this.props)
};
Or pass down projectdata
as a prop into your nested component, and include it as a parameter:
function getSuggestionValue(projectdata, suggestion) {
const job_id = projectdata.jobId;
const user_id = suggestion.id;
...
const autosuggestProps = {
getSuggestionValue,
projectdata: this.props.projectdata
};
But at that point, doesn't make a whole lot of sense to be passing the function itself as a property to begin with. You should consider simply referencing it statically from Autosuggest
.
Upvotes: 1
Reputation: 3384
As your this.props are undefined so that is the reason you get Cannot read property 'projectdata' of undefined. So what you can do is pass second param to the function like this.
getSuggestionValue(suggestion, props)
this inside the function resolve "this" of that function.
wherever you are calling getSuggestionValue function call like below:-
getSuggestionValue(suggestion, this.props) { const job_id = props.projectdata.jobId; }
I suppose you are calling the above function inside the class.
Upvotes: 0