How to get the length of the response from a fetch request? - json

I have got series of data that contains some objects in one array(json file) and it will be shown by react.
Here is my code:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
library:null,
perPage: 20,
currentPage: 1,
maxPage: null,
filter: ""
};
}
componentDidMount() {
fetch('/json.bc')
// Here I want to get the length of my respose
.then(response => response.text())
.then(text => {
var Maindata = JSON.parse(text.replace(/\'/g, '"'))
this.setState(state => ({
...state,
data: Maindata
}), () => {
this.reorganiseLibrary()
})
}).catch(error => console.error(error))
}
reorganiseLibrary = () => {
const { filter, perPage , data } = this.state;
let library = data;
if (filter !== "") {
library = library.filter(item =>
item.hotelinfo.hotelsearch.realname.toLowerCase().includes(filter)
);
}
library = _.chunk(library, perPage);
this.setState({
library,
currentPage: 1,
maxPage: library.length === 0 ? 1 : library.length
});
};
// Previous Page
previousPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage - 1
}));
// Next Page
nextPage = () =>
this.setState(prevState => ({
currentPage: prevState.currentPage + 1
}));
// handle filter
handleFilter = evt =>
this.setState(
{
filter: evt.target.value.toLowerCase()
},
() => {
this.reorganiseLibrary();
}
);
// handle per page
handlePerPage = (evt) =>
this.setState({
perPage: evt.target.value
}, () => this.reorganiseLibrary());
// handle render of library
renderLibrary = () => {
const { library, currentPage } = this.state;
if (!library || (library && library.length === 0)) {
return <div class="tltnodata">no result!</div>;
}
return library[currentPage - 1].map((item, i) => (
<input type="hidden" value={item.hotelinfo.hotelsearch.hotelid} name="hotelid"/>
));
};
render() {
const { library, currentPage, perPage, maxPage } = this.state;
return (
<div className="Main-wrapper">
<div class="filter_hotelname"><input value={this.state.filter} onChange={this.handleFilter} class="hotelName" /></div>
<div class="countHotel"> <span class="numbersearch"></span> // Here I want two show the count of items </div>
<div className="wrapper-data">
{this.renderLibrary()}
</div>
<div id="page-numbers">
<div class="nexprev">
{currentPage !== 1 && (
<button onClick={this.previousPage}><span class="fa-backward"></span></button>
)}
</div>
<div className="data_page-info">
{this.state.currentPage} از {this.state.maxPage}
</div>
<div class="nexprev">
{(currentPage < maxPage) && (
<button onClick={this.nextPage}><span class="fa-forward"></span></button>
)}
</div>
</div>
</div>
);
}
}
ReactDOM.render(<App/>, document.getElementById('Result'));
I want to find the length of response from a request with fetch. Also I want to know how to find the count of items that will be shown by renderLibrary . For example in json.bc we have 4 objects I want to show 4 in numbersearch span.

Using Fetch API you can find json response item length by running below code snippet. I have also added comment in code as well.
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
console.log(json);
alert("Number of item:"+json.length)
})
fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => {
//below method return promise based response by converting stream object to json
return response.json();
}).then(json => {
//Once succcessful callback return you can find length of number of item
alert(json.length)
})

You can use the length of the data array from the state to distinguish the number of items.
Since arrays start at 0, you will need to increment the count by one. Here's an example snippet below that you can use in your code sample.
<div class="countHotel"><span class="numbersearch">{this.state.data && this.state.data.length + 1}</span></div>

Related

How can i React ( get axios from Json and ReRandering my page)

Why am I asking this question (main return) is finsied, but board.writer is not drawing. how can i drawing this object
if my question is wrong way plz tell me . i will fix it
i tried this way
first use map function
make like this function renderUser = ({board_SEQ, content, writer,subject}) => { parameter}
const Home = () => {
const initboard = {
board_SEQ: '',
writer: '',
content: '',
subject: ''
};
const [boards, setBoard] = useState([]);
const load = () => {
axios.get('http://www.heon.shop:8080/api/boards')
.then((res) => {
const data = res.data;
setBoard(boards => [...boards, {
board_SEQ: (data[0].board_SEQ),
writer: data[0].writer,
content: data[0].content,
subject: data[0].subject
}]);
})
.catch((error) => {
console.log("error" + error);
}
);
}
useEffect(() => {
load();
console.log("useEffect");
}, []);
const renderUser = ({board_SEQ, content, writer, subject}) => {
return (
<div>
<li>he</li>
<li>{board_SEQ}</li>
<li>{content}</li>
<li>{writer}</li>
<li>{subject}</li>
</div>
);
}
return (
<div>
{boards.map(board => {
<h1> {board.writer}</h1>
})}
</div>
);
}
export default Home;
Maybe you can try like this,
<div>
{boards.map(board => renderUser(board)}
</div>
if you want to render item directly using (add return to the map):
<div>
{boards.map(board => {
return <h1> {board.writer}</h1>;
})}
</div>

How to get All JSON object from local JSON file in React functional component?

I'm using functional component and I'm getting JSOS object from local file And in component I'm setting that JSON in some state.
After that few object I spliced(deleted) from that setState. But again in onchange function I want all the JSON object but here I'm getting updated json means few are deleted, Is there any method I can store all JSON object in some place? can anybody help me in this.
const StudyDetails = () => {
const [supplyPlan, setSupplyPlan] = useState([]);
const getSupplyPlanDetails = useCallback(
async () => {
try {
const payload = {
studyName: studyDetails?.studyName
? studyDetails?.studyName
: query.get("name"),
country: [],
depot: [],
material: [],
site: [],
inTransientMaterial,
};
const res = await getSupplyPlan(payload);
//setSupplyPlan(res);
console.log(res)
// setSupplyPlan(supplyData)
} catch (err) {
setSupplyPlan([]);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
useEffect(() => {
getSupplyPlanDetails();
}, [ getSupplyPlanDetails]);
const onChange = (e) => {debugger
console.log(supplyData)
}
return (
<div>
<Checkbox
onChange={onChange}
>
In Transit
</Checkbox>
{supplyPlan?.map((item, index) => (
<Fragment key={index}>
<SupplyChain item={item} />
<Divider className="supply-chain-divider" />
</Fragment>
))}
</div>
)
}
I'm splicing few object in supplyChain component:
const SupplyChain = ({ item }) => {
useEffect(() => {
let data = [];
if (item && item.inTransit.length != 1) {
item &&
item.inTransit &&
item.inTransit.length > 0 &&
item.inTransit.map((intrans, index) => {
if (
intrans.from === item.depots?.packagingDepot?.[0]?.depotName &&
intrans.to === "sites"
) {
let directPath = item.inTransit.splice(index, 1);
setDirectSite(directPath);
}
setFilterJson(item.inTransit);
// eslint-disable-next-line react-hooks/exhaustive-deps
item = { ...item, filterJson: item.inTransit };
});
}
}
So if again when I click on onchange function I want all objects of JSON.
please someone help me in this

how to add css for div in React?

how to add css in such a way whenever i click and select on div the border and background colors of the div should be changed same goes for all for the selected and should be back to previous if deselected.
This is a seemingly stupid question, but I'm not a pro when it comes to css. I have created a multiple div for multiple selection of div, but the css file that came with it has completely changed the look of it and it looks different to my other controls - Is there a simple way of inheriting the look of another control?
codesanbox
I tried this way
const data = [
{
key: 1,
value: "four"
},
{
key: 2,
value: "fours"
}
];
export default function App() {
const initialState = data.map((item) => {
return { ...item, selected: false };
});
const [work, setWork] = React.useState(initialState);
const [state, setState] = React.useState();
const [selected, setSelected] = React.useState("");
console.log("work");
console.log(work);
console.log("work");
console.log("state");
console.log(state);
console.log("state");
React.useEffect(() => {
setState(
work.filter((person) => person.selected).map((person) => person.value)
);
setSelected(
work.filter((person) => person.selected).map((person) => person.value)
);
}, [work]);
const handleSelect = (value) => {
console.log("value", value);
const nextState = work.map((item) => {
if (item.value === value) {
return {
...item,
selected: !item.selected
};
}
return item;
});
setWork(nextState);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${selected === da.value ? "selected" : ""}`}
onClick={() => handleSelect(da.value)}
>
{da.value}
</div>
))}
</div>
);
}
I've done slight modifications in the code.
Following code would help you get the desired results.
const handleSelect = (key) => {
const updatedItems = [];
work.forEach((item) => {
updatedItems.push ({
...item,
selected: item.key === key
});
});
setWork(updatedItems);
};
return (
<div className="parent">
{work.map((da) => (
<div
className={`child ${da.selected ? "selected" : ""}`}
onClick={() => handleSelect(da.key)}
>
{da.value}
</div>
))}
</div>
);

How can I correctly implement 'load more' button in react

I have this code and it gives out 12 objects that I map
class PokemonList extends React.Component{
constructor(props){
super(props);
this.state = {
pokemonList: [],
apiTemplateUrl: "https://pokeapi.co/api/v2/pokemon?offset={number}&limit=12"
}
this.loadMore()
}
loadMore=()=>{
let num = 0;
let apiTemplateUrl = this.state.apiTemplateUrl;
let apiUrl = apiTemplateUrl.replace("{number}",num)
fetch('https://pokeapi.co/api/v2/pokemon?offset=0&limit=12')
.then((response) => {
return response.json();
})
.then((listPokemons) => {
listPokemons.results.forEach((aboutPokemon) => {
let aboutPokemonUrl = aboutPokemon.url;
fetch(aboutPokemonUrl)
.then((response) => {
return response.json();
})
.then((pokeData) => {
this.setState(prevState => ({
pokemonList: [...prevState.pokemonList, pokeData]
}))
})
})
})
}
Component with load more button
render() {
return (
<div className="load-more">
<button onClick={()=>this.props.loadMore()}>Load More</button>
</div>
);
}
in order for me to give the next 12 I need to replace 0 with 12 here and change fetch
https://pokeapi.co/api/v2/pokemon?offset=0&limit=12
But how can I do this right
Thank you!
You should store your offset in the state. Then update the offset after the fetch.
First add the offset to your state
this.state = {
pokemonList: [],
offset: 0,
};
Then you can fetch using that offset.
fetch(`https://pokeapi.co/api/v2/pokemon?offset=${this.state.offset}&limit=12`)
Then you can update the state how you choose (after your second then?).
.then(() => {
this.setState(prevState => ({
...prevState,
offset: prevState.offset + 12,
}));
})
Also, you don't need to run this.loadMore() in your constructor. You can run it in componentWillMount().
The api also returns the next value, so maybe you want to store that instead (listPokemons.next)...
Use JSX like this to render elements from state:
render() {
const pokes = this.state.pokemonList
return (
<div className="load-more">
<button onClick={()=>this.props.loadMore()}>Load More</button>
{
pokes.map(poke => {
return (<div>{poke.name}</div>)
}
}
</div>
);
}

React-Native render json from fetch

I have a fetch returning on ComponentDidMount(). Trying to get the response to render on the page.
I have set the state as follows:
this.state = {
loading: true,
file: null,
video: null,
marks: []
};
and my fetch:
componentDidMount() {
return fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
this.setState({
loading: false,
marks: data.mark
}, () => {
console.log(data.mark);
console.log(this.state.marks);
// const dataMap = data.mark.map((item) => {
// return {
// key: item.id,
// label: item.mark
// };
// });
});
})
.catch(err => console.log(err));
}
Now my render inside of the return:
const { marks } = this.state;
<FlatList
data={marks}
renderItem={({ item }) => <Text>{item.mark}</Text>}
keyExtractor={(item, index) => index}
/>
Do I have to map the data then try to render it??
OUTPUT OF console.log(this.state.marks):
{ _id: '5b61e47a55a0000aa980fab1', mark: 'ItHe', __v: 0 }
The mark is a pseudorandom string that can contain letters and numbers created on the backend
As this.state.marks is an object. First, you need to convert it to this form [{}]. You can do the following changes to make it work.
fetch('http://10.0.2.2:8080/marks/createMark')
.then(response => response.json())
.then((data) => {
let marks = [data.mark]; //Add this line
this.setState({
loading: false,
marks: marks // Change this line
}, () => {
....
Rest of your code
marks is an array but you're not sharing what each object in the array looks like. If it's an array of strings, you're good but if it's an object, you'll need to destructure it and pull out the string you're looking to render.
<Text>{item.mark.someKeyWhoseValueIsAString}</Text