score:5
Cannot read property 'saved' of undefined
You are not correctly referencing this.state
for saved
or headline
.
Cannot read property 'state' of undefined
Either add a constructor and bind this
to your saved
function.
constructor(props) {
super(props);
this.saved = this.saved.bind(this);
}
saved() {
this.saved.push(this.headline);
//alert('this is saved kind of');
}
Or define saved
as an arrow function to bind this
saved = () => {
this.saved.push(this.headline);
//alert('this is saved kind of');
}
Should be
saved() {
const { headline, saved } = this.state;
this.setState({ saved: [...saved, headline] });
}
or
saved = () => {
const { headline, saved } = this.state;
this.setState({ saved: [...saved, headline] });
}
UPDATE: Save a specific post/headline
I see now, if you wish to save a specific headline then you need to update the signature of your saved
function and how you call it.
saved = headline => {
this.setState(
prevState => ({ saved: [...prevState.saved, headline] })
);
}
and when you invoke it as a callback
<button
className="btn-primary btn mt-2 mb-4"
onClick={() => this.saved(post)} // pass the current post defined in the map callback
>
Add this article
</button>
One minor comment about naming, consistently referencing the same "object" the same way throughout code goes a long way in helping readability. I.E. how you reference headlines, posts, and articles. Pick one and be consistent.
this.state.headlines
=> this.state.headlines.map(headline => ...
this.state.posts
=> this.state.posts.map(post => ...
this.state.articles
=> this.state.articles.map(article => ...
score:2
saved() {
this.saved.push(this.headline);
//alert('this is saved kind of');
}
You cannot defined class methods like this without writing a constructor like this:
class NewsHero extends Component {
constructor(props){
super(props)
this.saved = this.saved.bind(this)
}
...the rest of everything you wrote
}
Without doing this, your saved
function is not bound to the instance of the class. Its silly, yes, but that's how class methods work in javasript. The other option is to use an arrow function, which preserves the context if this
:
saved = () => {
this.saved.push(this.headline);
//alert('this is saved kind of');
}
I think this is faster and cleaner, and its pretty commonly used.
That is problem 1. Problem 2 is that it appears you are trying to modify the state object directly when writing this.saved.push(this.headline)
. That's not how to do it. To modify your state, you need to use the this.setState
function:
saved = () => {
this.setState({
saved: whatever you want this to be
})
}
But it looks like you are already setting your state correctly in your fetch call, so I'm not sure what you're trying to accomplish with your saved
function...?
Source: stackoverflow.com
Related Query
- Push object from JSON rest api into empty array not working in React
- Add value from input into array is not working in React
- React push object into array and map error map not a function
- array object working if we hardcode data but not working when we populate data from Node js to react js
- push an object to an array not working on Javascript react
- react get data from rest api with axios and and useEffect redering empty array plus array with data
- React Context API not working from custom NPM component library
- React.js: loading JSON data with Fetch API and props from object array
- React Apollo first object from subscription not being merge into previous data it actually gets removed
- React Firestore data retrieval into array not working
- React not turning HTML string from JSON into text
- React onClick pass object ID from a JSON array
- How to push an object into an array with React Hooks
- array of selected values which I want to delete from state is not working as expected - React
- Fetch API not working with Rails + React from Webpacker
- Push an object from an array into another array javascript
- How to store data from json API response into array in ReactJS?
- how to push an item into an array if it is inside a javascript object [state.lastValue.push is not a function]
- Why is map not working with json from api, while locally created json works fine? React
- Using data from API JSON object using Axios and React
- Image path not working in React as I tried to use use Image path inside an object which is also inside of an array
- React js iteration of JSON array is not working
- How can I filter json data from api call in react into different sections of the component
- How to send FormData attribute with an array of strings from React Client to Django + Django Rest Framework API
- React map object and embedded object from JSON and convert to single array for state
- Extracting data from json object from API with JavaScript React Native
- Check if object of any array exist in an another array, if not exists then push onto another array , or else remove it from another array
- How send files in JSON structure from React app to API REST NET Core
- Fetched data from Rest API does not appear in the browser in React
- Access Object inside Array in React JSON API Call
More Query from same tag
- Is there any way that I can add another value to a key in an object within React?
- show data from object on click
- How to make a react + d3 stacked bar chart grouped?
- ReactJS: Form onSubmit failing to call callback
- React state changed not re rendering child
- How do I modify the search query on a subscription?
- How can you trigger a rerender of a React js component every minute?
- Hold input values in local state, but pass to parent to submit form
- Multiple and Multi selected Checkboxes in ReactJS
- Using custom templates with Preact JS
- Web API Push on iOS/Safari - React App. Really no Service in 2021?
- React reconciliation - props diff
- Home Component is not rendering when the app loads on Github Pages but loading on Localhost
- Code coverage is not working for some files in WebStorm
- Error: Stripe: Unknown arguments ([object Object]). Did you mean to pass an options object?
- extract value from url using react router
- How to iterate over array of objects in ReactTable so as to display the data?
- Using emailjs in react(not typescript)
- TypeError: firebase.auth() is not a function
- React Router v4 Match transitions using React Motion
- how to write a handler for multiple checkboxes in a functional component?
- React app deployed on heroku immediately crashes code=H10
- How can I display item in ToDo List
- How to replace the string after some character using index in javascript?
- React app works on Chrome, but not Firefox
- Not able to listen for data changes from API
- React. Redirect by button click in React with react-router-dom
- Queried parameter is null
- Way to make a POST request to server to INSERT a record and retrieve the generated ID in the Client
- How to test the child component render text after the button on the parent component click with react testing library?