Show new data and replace the old data in the same position - javascript

Goal:
Get the second data by pressing the button and the list should display in the html page. It should replace the old data with a new data.
Problem:
I cannot make the button to be working in order to display the result on the webpage. Show new data and replace the old data.
What part am I missing?
Info:
*I'm newbie in Reactjs
Stackblitz:
https://stackblitz.com/edit/react-fetch-data-from-api-f632fh?
Thank you!
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
class App extends Component {
constructor() {
super();
this.state = {
name: 'React',
data: null
};
}
componentDidMount = () => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(data => {
console.log(data);
this.setState({ data });
});
};
getSecondData() {
fetch('https://fakerestapi.azurewebsites.net/api/v1/Activities')
.then(res => res.json())
.then(data => {
console.log(data);
this.setState({ data });
});
}
showAlert() {
alert("I'm an alert");
}
render() {
return (
<div>
<button onClick={this.getSecondData}>ASDF</button>
<p>Start editing to see some magic happen :)</p>
<ul>
{this.state.data &&
this.state.data.map(user => <li id={user.id}>{user.id}</li>)}
</ul>
</div>
);
}
}
render(<App />, document.getElementById('root'));

You were missing a couple of things.
First of all, you should never setState like that. Instead, always use prevState. Like this:
this.setState(prevState => ({
...prevState,
data
}));
Second, you either need to bind the function you are creating in the constructor like this: this.getSecondData = this.getSecondData.bind(this)
You read more about that here: https://reactjs.org/docs/handling-events.html
Or better solution is to just use arrow functions.
The correct working solution can be found here:
https://stackblitz.com/edit/react-fetch-data-from-api-znjdf6

Related

React function takes two button clicks to run

I have an array of Notes that I get from my database, the notes objects each have a category assigned to it. There are also buttons that allow the user to filter the notes by category and only render the ones with the corresponding one.
Now, it's all working pretty well but there's one annoying thing that I can't get rid of: whenever I click on any of the buttons: <button onClick={() => {handleClick(categoryItem.category)}}>{categoryItem.category}</button>, the filterNotes() function is only called on the second click. I suspect it has to do something with me calling setState() twice, or maybe with the boolean that I set in the functions, but I tried various combinations to call the function on the first click, but to no avail so far.
Here's my MainArea code:
import React, { useState, useEffect } from "react";
import Header from "./Header";
import Footer from "./Footer";
import ListCategories from "./ListCategories";
import Note from "./Note";
import axios from "axios"
function CreateArea(props) {
const [isExpanded, setExpanded] = useState(false);
const [categories, setCategories] = useState([])
const [notes, setNotes] = useState([])
const [fetchB, setFetch] = useState(true)
const [filterOn, setFilter] = useState(false)
const [note, setNote] = useState({
title: "",
content: "",
category: ''
});
useEffect(() => {
fetch('http://localhost:5000/categories')
.then(res => res.json())
.then(json => setCategories(json))
}, [])
useEffect(() => {
if(fetchB) {
fetch('http://localhost:5000/notes')
.then(res => res.json())
.then(json => {
console.log(json)
setNotes(json)
setFetch(false)
})
}
}, [fetchB])
function handleChange(event) {
const { name, value } = event.target;
console.log("handleChange called")
setNote(prevNote => {
return {
...prevNote,
[name]: value
};
});
}
function submitNote(e){
e.preventDefault();
axios.post("http://localhost:5000/notes/add-note", note)
.then((res) => {
setNote({
category: '',
title: "",
content: ""
})
setFetch(true)
console.log("Note added successfully");
console.log(note)
})
.catch((err) => {
console.log("Error couldn't create Note");
console.log(err.message);
});
}
function expand() {
setExpanded(true);
}
function filterNotes(category){
if(filterOn){
fetch('http://localhost:5000/notes')
.then(res => res.json())
.then(json => {
console.log("filter notes")
setNotes(json)
setNotes(prevNotes => {
console.log("setNotes called with category " + category)
return prevNotes.filter((noteItem) => {
return noteItem.category === category;
});
});
setFilter(false)
})
}
}
return (
<div>
<Header/>
<ListCategories categories={categories} notes={notes} filterNotes={filterNotes} setFilter={setFilter} filterOn={filterOn} setFetch={setFetch}/>
<form className="create-note">
{isExpanded && (
<input
name="title"
onChange={handleChange}
value={note.title}
placeholder="Title"
/>
)}
<textarea
name="content"
onClick={expand}
onChange={handleChange}
value={note.content}
placeholder="Take a note..."
rows={isExpanded ? 3 : 1}
/>
<select
name="category"
onChange={handleChange}
value={note.category}>
{
categories.map(function(cat) {
return <option
key={cat.category} value={cat.value} > {cat.category} </option>;
})
}
</select>
<button onClick={submitNote}>Add</button>
</form>
<Note notes={notes} setFetch={setFetch}/>
<Footer/>
<button onClick={()=>{setFetch(true)}}>All</button>
</div>
);
}
export default CreateArea;
And ListCategories where I get call the function and get the chosen category from the buttons:
import React, { useState } from "react";
import CreateCategory from "./CreateCategory";
export default function ListCategories(props) {
function handleClick(category){
props.setFilter(true)
props.filterNotes(category)
}
return (
<div className="category-group">
<CreateCategory/>
<div className="btn-group">
{props.categories.map((categoryItem, index) =>{
return(
<button onClick={() => {handleClick(categoryItem.category)}}>{categoryItem.category}</button>
)
})}
</div>
</div>
)
}
I'm not sure what the best practice is with such behaviour - do I get the notes from the database each time as I'm doing now or should I do something completely different to avoid the double-click function call?
Thanks in advance for any suggestions!
Your issue is this function:
function handleClick(category){
props.setFilter(true)
props.filterNotes(category)
}
Understand that in React, state is only updated after the current execution context is finished. So in handleClick() when you call setFiler(), that linked filterOn state is only updated when the rest of the function body finishes.
so when your filterNotes() function is called, when it evaluates filterOn, it is still false, as it was initially set. After this function has executed, the handleClick() function has also finished, and after this, the filterOn state now equals true
This is why on the second click, the desired rendering effect occurs.
There are multiple ways to get around this, but I normally use 'render/don't-render' state by including it as an embedded expression in the JSX:
<main>
{state && <Component />}
</main>
I hope this helps.
You diagnosed the problem correctly. You shouldn't be using state like you would a variable. State is set asynchronously. So, if you need to fetch some data and filter it, do that and THEN add the data to state.
function filterNotes(category){
fetch('http://localhost:5000/notes')
.then(res => res.json())
.then(json => {
const filtered = json.filter((noteItem) => (noteItem.category === category));
setNotes(filtered);
})
}
}
It's not clear to me why you would need the filterOn state at all.
Depending on how your frequently your data is updated and if you plan on sharing data across users, the answer to this question will vary.
If these notes are specific to the user then you should pull the notes on load and then store them in a local state or store. Write actions that can update the state or store so that this isn't coupled with your react UI rendering. Example: https://redux.js.org/ or https://mobx.js.org/README.html.
Then update that store and your remote database accordingly through dispatching actions. This avoids lots of calls to the database and you can perform your filtering client-side as well. You can then also store data locally for offline use through this method so if it's for a mobile app and they lose internet connection, it'll still render. Access the store's state and update your UI based on that. Specifically the notes and categories.
If you have multiple users accessing the data then you'll need to look at using websockets to send that data across clients in addition to the database. You can add listeners that look for this data and update that store or state that you will have created previously.
There are many approaches to this, this is just an approach I would take.
You could also create a context and provider that maintains your state on the first load and persists after that. Then you can avoid passing down state handlers through props

Map is undefined in React

I am using fetch to get API data that I'm using to create a drop down that I will add routes too. I've done this a couple of times before but I used axios previously but I just wanted to get familiar with fetch as well. Can anyone see the problem of why map would be undefined?
import React, { Component } from 'react'
class Fetchheroes extends Component {
constructor() {
super();
this.state = {
heroes: [],
}
}
componentDidMount(){
fetch('https://api.opendota.com/api/heroStats')
.then(results => {
return results.json();
}).then(data =>{
let heroes = data.results.map((hero) =>{
return(
<div key={hero.results}>
<select>
<option>{hero.heroes.localized_name}</option>
</select>
</div>
)
})
this.setState({heroes: heroes});
console.log("state", this.state.heroes);
})
}
render(){
return(
<div>
<div>
{this.state.heroes}
</div>
</div>
)
}
}
export default Fetchheroes
You have a bad mapping about data. You need to use data instead of data.result and you have a bad key value because results are not unique key in that case. You also don't need your hero.heroes.localized_name just hero.localized_name. I made an example in codesandbox.
https://codesandbox.io/s/clever-hodgkin-7qo6p
Edit
I made another example when I put all records to one select, not for multiple selects, maybe is that what you need or someone else :).
https://codesandbox.io/s/bold-grass-gv0wc

React axios request in ComponentDidMount not passing data as props to component

Hi guys I can't see my Error here hope someone can hlep...
This is my fetch Data class:
export default class Auftrag extends Component {
state = {
auftraege: "Test",
};
getAuftraege = () => {
axios.get("Auftraege/auftraege").then(e => {
this.setState({
auftraege: e.data,
});
console.log(e.data);
});
};
componentDidMount() {
this.getAuftraege();
}
render() {
return (
<>
<AuftragDisplay test={this.state.auftraege} ></AuftragDisplay>
</>
);
}
}
And this is my constructor in my Display class:
constructor(props) {
super(props);
console.log(props);
}
The axios Request is getting fired and I get the right data in my console. But It is not getting passed to my Component.
Hope someone knows whats wrong and can help me
SOLVED:
Thx to san I tried it and could solve the problem. I got the data passed but console.log() was called before the update so I got the old data. THX again
Your code looks fine. you can see below same code with different api as an example
class Auftrag extends Component {
state = {
auftraege: "Test",
};
getAuftraege = () => {
axios
.get("https://jsonplaceholder.typicode.com/posts/1")
.then(e => this.setState({auftraege: e.data}))
};
componentDidMount() {
this.getAuftraege();
}
render() {
return (
<>
<AuftragDisplay test={this.state.auftraege} ></AuftragDisplay>
</>
);
}
}
const AuftragDisplay = ({test}) =><h2>Hi--->{test.title}</h2>
Just put the state inside constructor of Auftrag class, I should work.

Fetch one JSON object and use it reactjs

I'm very new to JS and ReactJS and I try to fetch an endpoint which gives me a JSON Object like this :
{"IDPRODUCT":4317892,"DESCRIPTION":"Some product of the store"}
I get this JSON Object by this endpoint :
http://localhost:3000/product/4317892
But I dont how to use it in my react application, I want to use those datas to display them on the page
My current code looks like this but it's not working and I'm sure not good too :
import React, {Component} from 'react';
class Products extends Component {
constructor(props){
super(props);
this.state = {
posts: {}
};
};
componentWillMount() {
fetch('http://localhost:3000/product/4317892')
.then(res => res.json())
.then(res => {
this.setState({
res
})
})
.catch((error => {
console.error(error);
}));
}
render() {
console.log(this.state)
const { postItems } = this.state;
return (
<div>
{postItems}
</div>
);
}
}
export default Products;
In the console.log(this.state) there is the data, but I'm so confused right now, dont know what to do
Since I'm here, I have one more question, I want to have an input in my App.js where the user will be able to type the product's id and get one, how can I manage to do that ? Passing the data from App.js to Products.js which is going to get the data and display them
Thank you all in advance
Your state doesn't have a postItems property which is considered undefined and react therefore would not render. In your situation there is no need to define a new const and use the state directly.
Also, when you setState(), you need to tell it which state property it should set the value to.
componentWillMount() {
fetch('http://localhost:3000/product/4317892')
.then(res => res.json())
.then(res => {
this.setState({
...this.state, // Not required but just a heads up on using mutation
posts: res
})
})
.catch((error => {
console.error(error);
}));
}
render() {
console.log(this.state)
return (
<div>
<p><strong>Id: {this.state.posts.IDPRODUCT}</strong></p>
<p>Description: {this.state.posts.DESCRIPTION}</p>
</div>
);
}
I have got 3 names for the same thing in your js: posts, postItems and res.
React can not determine for you that posts = postItems = res.
So make changes like this:
-
this.state = {
postItems: {}
};
-
this.setState({
postItems: res
});
-
return (
<div>
{JSON.stringify(postItems)}
<div>
<span>{postItems.IDPRODUCT}</span>
<span>{postItems.DESCRIPTION}</span>
</div>
</div>
);
{postItems["IDPRODUCT"]}
Will display the first value. You can do the same for the other value. Alternatively, you can put
{JSON.stringify(postItems)}
With respect to taking input in the App to use in this component, you can pass that input down through the props and access it in this component via this.props.myInput. In your app it'll look like this:
<Products myInput={someInput} />

Calling a function from another in ReactJs

I have the following ReactJS component:
articles_list.jsx
import React from 'react';
import marked from 'marked';
import './articles_list.css';
export default class ArticlesList extends React.Component {
constructor(props) {
super(props);
this.state = {
articles: null
}
}
componentWillMount() {
fetch('/articles_all')
.then(res => res.json())
.then(json => {
this.setState({
articles: json.articles
});
});
}
handleClick(e) {
e.preventDefault();
var elem = e.target;
var file = elem.getAttribute('data-file').split('.')[0];
fetch('/article/'+file, {
headers: {
'Accept': 'text/markdown'
}
})
.then(res => res.text())
.then(txt => marked(txt))
.then(html => document.getElementById('article-text').innerHTML = html)
}
render() {
var teste = []
if (this.state.articles === null) {
teste.push(<div id="no-articles" key="1">No articles</div>)
} else {
{this.state.articles.forEach( function(element, index) {
teste.push(<div onClick={this.handleClick} data-file={element.file} className="articles-menu-item" key={index.toString()}>{element.title}</div>);
}.bind(this))}
}
return(
<div className="articles-list">
<div className="articles-list-title">
ARTICLES
</div>
<div id="menu-body" className="menu-body">{teste}</div>
</div>
);
}
}
As you may see, it fetches as list of articles and creates links. When these links are clicked the corresponding article is load in a certain area of the page.
The code is working perfectly, but now I need to load a certain article before any of the links to be clicked. Then I decided to break the code inside handleClick like this:
loadArticle(file) {
fetch('/article/'+file, {
headers: {
'Accept': 'text/markdown'
}
})
.then(res => res.text())
.then(txt => marked(txt))
.then(html => document.getElementById('article-text').innerHTML = html)
}
handleClick(e) {
e.preventDefault();
var elem = e.target;
var file = elem.getAttribute('data-file').split('.')[0];
loadArticle(file);
}
My idea with this is to invoke loadArticle inside render to load an specific article when the component loads, like this:
return(
<div className="articles-list">
<div className="articles-list-title">
ARTICLES
</div>
<div id="menu-body" className="menu-body">{teste}{this.loadArticle('my_specific_article')}</div>
</div>
);
It works and now my_specific_article loads correctly when I navigate to the page. But...
But now when I click the links, that were working fine before, I got an error
Uncaught ReferenceError: loadArticle is not defined
And if I do
handleClick(e) {
e.preventDefault();
var elem = e.target;
var file = elem.getAttribute('data-file').split('.')[0];
this.loadArticle(file);
}
using this, then I get
Uncaught TypeError: Cannot read property 'loadArticle' of null
How should I deal with this? I know it is a matter of context but, being new to ReactJS, I really don't know how to proceed.
EDIT
This is not a duplicate of this question, as it was marked. The reason is simple. In the mentioned question the function to bind is a event handler and in my problem a function being called by another. In fact, my event handler (similar to the other question) was working fine without the bind, then we are not talking about the same thing.
You must bind your custom functions in the constructor.
Modify your constructor like this.
constructor(props) {
super(props);
this.state = {
articles: null
}
this.handleClick = this.handleClick.bind(this);
this.loadArticle = this.loadArticle.bind(this);
}
Now everywhere you should call this function as this.handleClick & this.loadMore.
You can read about other binding patterns here. The one I've mentioned is number 4.
That is the preferred way in facebook docs as well.

Categories

Resources