I want to fetch data and display it in a react page - javascript

I'm new to reactjs, I want to fetch and display data from my database table in a react page ,i wrote a code following a tutorial but i don't know how to correct it.
This is the data :
and this is the code i'm writing
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function Companies() {
const [companies, setCompanies] = useState(initialState: [])
useEffect( effect: () => {
companydata()
}, deps: [])
const companydata = async () => {
const {data}= await axios.get("http://localhost:5000/api/v1/companies");
setCompanies(data);
}
return (
<div className="companies">
{companies.map(companies => (
<div key={companies.CompanyId}>
<h5>{companies.CompanyName}</h5>
</div>
))}
</div>
);
}
export default Companies;

useEffect( effect: async () => {
await companydata()
}, deps: [])
have you tried adding async and await inside useEffect hook

Try to change your code like this:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
function Companies() {
const [companies, setCompanies] = useState([]);
useEffect(() => {
companydata();
}, []);
const companydata = async () => {
const { data } = await axios.get('http://localhost:5000/api/v1/companies');
setCompanies(data);
};
return (
<div className='companies'>
{companies.map((comp) => (
<div key={comp.CompanyId}>
<h5>{comp.CompanyName}</h5>
</div>
))}
</div>
);
}
export default Companies;

Related

how to dynamically import a react component and call it?

I have a react component that contains an SVG image.
and i import it like this
import MessageIcon from '../static/styles/svg/messageIcon';
However as part of code splitting, i want to dynamically import it instead of static import.
I tried like this but does not work
import('../static/styles/svg/messageIcon').then(MessageIcon => { return <MessageIcon /> });
can anyone tell me how i can dynamically import and call this component? thanks in advance
You can import dynamical like this :
import React, { useEffect, useState } from "react";
const App = () => {
const [state, setState] = useState<any>();
useEffect(() => {
(async () => {
const i = await import("../../assets/img/user.svg");
setState(i);
})();
}, []);
return <img alt={"test dynamic"} src={state?.default} />;
};
export default App;
Also, you can write it with ref too:
import React, { useEffect, useRef } from "react";
const App = () => {
const ref = useRef<any>();
useEffect(() => {
(async () => {
const i = await import("../../assets/img/user.svg");
ref.current.src = i.default;
})();
}, []);
return <img alt={"test dynamic"} ref={ref} />;
};
export default App;
import dynamical React component
import React from "react";
const App = () => {
const nameIcon = "iconMessage";
const IconMessage = React.lazy(() => import(/* webpackChunkName: "icon" */ `./${nameIcon}`));
return <IconMessage />;
};
export default App;

Why does it make a mistake?

The code below is not working. It doesn't see the apikey in parentheses.I couldn't understand what I had to do here. Is it a problem with the hooks structure?
import React, { useEffect } from 'react';
import MovieListing from "../MovieListing/MovieListing";
import movieApi from "../../common/apis/movieApi";
import { APIKey } from "../../common/apis/MovieApiKey"; //the program does not see this
import "./Home.scss";
import { useDispatch } from 'react-redux';
import { addMovies } from '../../features/movies/movieSlice';
const Home = () => {
const dispatch = useDispatch();
useEffect(() => {
const movieText = "Harry";
const fetchMovies = async () => {
const response = await movieApi.get('?apiKey=${APIKey}&s=${movieText}&type=movie')
.catch((err) => { console.log("Err :", err) });
dispatch(addMovies)(response.data); //api key does not see this
};
fetchMovies();
}, []);
return (
<div>
<div className='banner-img'></div>
<MovieListing />
</div>
);
};
export default Home;

Call api on page load in React

I am learning React and I am trying to call an API on my page load, but I haven't had much success so far. I am trying to call an API which will pull an JSON that is used to fill my grid. Here is my code:
import React, { Component, useCallback, useState, useEffect } from "react";
import axios from 'axios';
import './styles.css';
import '#progress/kendo-theme-default/dist/all.css';
import { Grid, GridColumn, GridToolbar } from "#progress/kendo-react-grid";
import { DropDownList } from "#progress/kendo-react-dropdowns";
import { GridPDFExport } from "#progress/kendo-react-pdf";
import { ExcelExport } from "#progress/kendo-react-excel-export";
export function GridTable1({}) {
const [ grid1, setGrid1 ] = useState();
const fillTable= async () => {
await axios
.get('http://11.11.21.111:8888/api/v1/CheckTablespace')
.then((res) => {
setGrid1(res.rlista)
});
console.log('Log this');
}
useEffect(() => {
fillTable();
}, [])
return (
...
...
);
}
The console log isn't logged, so I don't know what to do. Help would be very much appreciated
Try this!!!
export function GridTable1() {
const [ grid1, setGrid1 ] = useState();
useEffect(() => {
axios
.get('http://11.11.21.111:8888/api/v1/CheckTablespace')
.then((res) => {
setGrid1(res.rlista)
});
console.log('Log this');
}, []);
return (
{grid1 &&
<div>
...your HTML
</div>}
);
}

Sibling component not re-rerendering on state change (using useEffect, useState and Context)

In my Main.js I create a first global state with a username and a list of users I'm following.
Then, both the Wall component and FollowingSidebar render the list of follows and their messages (plus the messages of the main user).
So far so good. But in a nested component inside FollowingSidebar called FollowingUser I have an onClick to remove a user. My understanding is that, because I change the state, useEffect would take care of the Wall component to re-render it, but nothing happens... I've checked several examples online but nothing has helped my use case so far.
Needless to say I'm not overly experienced with React and Hooks are a bit complex.
The code here:
Main.js:
import React, { useEffect, useState } from "react";
import ReactDom from "react-dom";
import db from "./firebase.js";
// Components
import Header from "./components/Header";
import FollowingSidebar from "./components/FollowingSidebar";
import SearchUsers from "./components/SearchUsers";
import NewMessageTextarea from "./components/NewMessageTextarea";
import Wall from "./components/Wall";
// Context
import StateContext from "./StateContext";
function Main() {
const [mainUser] = useState("uid_MainUser");
const [follows, setFollows] = useState([]);
const setInitialFollows = async () => {
let tempFollows = [mainUser];
const user = await db.collection("users").doc(mainUser).get();
user.data().following.forEach(follow => {
tempFollows.push(follow);
});
setFollows(tempFollows);
};
useEffect(() => {
setInitialFollows();
}, []);
const globalValues = {
mainUserId: mainUser,
followingUsers: follows
};
return (
<StateContext.Provider value={globalValues}>
<Header />
<FollowingSidebar />
<SearchUsers />
<NewMessageTextarea />
<Wall />
</StateContext.Provider>
);
}
ReactDom.render(<Main />, document.getElementById("app"));
if (module.hot) {
module.hot.accept();
}
FollowingSidebar component:
import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import StateContext from "../StateContext";
import FollowingUser from "./FollowingUser";
export default function FollowingSidebar() {
const { followingUsers } = useContext(StateContext);
const [users, setUsers] = useState(followingUsers);
useEffect(() => {
const readyToRender = Object.values(followingUsers).length > 0;
if (readyToRender) {
db.collection("users")
.where("uid", "in", followingUsers)
.get()
.then(users => {
setUsers(users.docs.map(user => user.data()));
});
}
}, [followingUsers]);
return (
<section id="following">
<div className="window">
<h1 className="window__title">People you follow</h1>
<div className="window__content">
{users.map((user, index) => (
<FollowingUser avatar={user.avatar} username={user.username} uid={user.uid} key={index} />
))}
</div>
</div>
</section>
);
}
FollowingUser component:
import React, { useState, useContext } from "react";
import db from "../firebase.js";
import firebase from "firebase";
import StateContext from "../StateContext";
export default function FollowingUser({ avatar, username, uid }) {
const { mainUserId, followingUsers } = useContext(StateContext);
const [follows, setFollows] = useState(followingUsers);
const removeFollow = e => {
const userElement = e.parentElement;
const userToUnfollow = userElement.getAttribute("data-uid");
db.collection("users")
.doc(mainUserId)
.update({
following: firebase.firestore.FieldValue.arrayRemove(userToUnfollow)
})
.then(() => {
const newFollows = follows.filter(follow => follow !== userToUnfollow);
setFollows(newFollows);
});
userElement.remove();
};
return (
<article data-uid={uid} className="following-user">
<figure className="following-user__avatar">
<img src={avatar} alt="Profile picture" />
</figure>
<h2 className="following-user__username">{username}</h2>
<button>View messages</button>
{uid == mainUserId ? "" : <button onClick={e => removeFollow(e.target)}>Unfollow</button>}
</article>
);
}
Wall component:
import React, { useState, useEffect, useContext } from "react";
import db from "../firebase.js";
import Post from "./Post";
import StateContext from "../StateContext";
export default function Wall() {
const { followingUsers } = useContext(StateContext);
const [posts, setPosts] = useState([]);
useEffect(() => {
console.log(followingUsers);
const readyToRender = Object.values(followingUsers).length > 0;
if (readyToRender) {
db.collection("posts")
.where("user_id", "in", followingUsers)
.orderBy("timestamp", "desc")
.get()
.then(posts => setPosts(posts.docs.map(post => post.data())));
}
}, [followingUsers]);
return (
<section id="wall">
<div className="window">
<h1 className="window__title">Latest messages</h1>
<div className="window__content">
{posts.map((post, index) => (
<Post avatar={post.user_avatar} username={post.username} uid={post.user_id} body={post.body} timestamp={post.timestamp.toDate().toDateString()} key={index} />
))}
</div>
</div>
</section>
);
}
StateContext.js:
import { createContext } from "react";
const StateContext = createContext();
export default StateContext;
The main issue is the setting of state variables in the Main.js file (This data should actually be part of the Context to handle state globally).
Below code would not update our state globally.
const globalValues = {
mainUserId: mainUser,
followingUsers: follows
};
We have to write state in a way that it get's modified on the Global Context level.
So within your Main.js set state like below:
const [globalValues, setGlobalValues] = useState({
mainUserId: "uid_MainUser",
followingUsers: []
});
Also add all your event handlers in the Context Level in Main.js only to avoid prop-drilling and for better working.
CODESAND BOX DEMO: https://codesandbox.io/s/context-api-and-rendereing-issue-uducc
Code Snippet Demo:
import React, { useEffect, useState } from "react";
import FollowingSidebar from "./FollowingSidebar";
import StateContext from "./StateContext";
const url = "https://jsonplaceholder.typicode.com/users";
function App() {
const [globalValues, setGlobalValues] = useState({
mainUserId: "uid_MainUser",
followingUsers: []
});
const getUsers = async (url) => {
const response = await fetch(url);
const data = await response.json();
setGlobalValues({
...globalValues,
followingUsers: data
});
};
// Acts similar to componentDidMount now :) Called only initially
useEffect(() => {
getUsers();
}, []);
const handleClick = (id) => {
console.log(id);
const updatedFollowingUsers = globalValues.followingUsers.filter(
(user) => user.id !== id
);
setGlobalValues({
...globalValues,
followingUsers: updatedFollowingUsers
});
};
return (
<StateContext.Provider value={{ globalValues, handleClick }}>
<FollowingSidebar />
</StateContext.Provider>
);
}
export default App;

Console log showing more than expected while using React Hooks

I am trying to fetch Data from an Api. I am getting the required result but when I try to console log it , it is console logging 4 times.
This is my app.js where I am using the fetchData.
import React, {useEffect, useState} from 'react';
import styles from './App.modules.css';
import {Header, Cards, Footer, Map, Table, Statecards} from './components/exports';
import {fetchData} from './api';
function App() {
const [data, setData] = useState({});
useEffect(() => {
const settingData = async () => {
const data = await fetchData();
setData(data);
}
settingData();
}, []);
console.log(data);
return <div className = {styles.container}>
<Header />
</div>
;
}
export default App;
This is the fetchData function
import axios from 'axios';
const url = 'https://api.covid19india.org/data.json';
export const fetchData = async () => {
try{
const response = await axios.get(url);
return response;
}
catch(err){
console.log(err);
}
};
The console.log in the app.js is giving 4 console logs as below
I am not being able to figure out what's wrong.
const settingData = async () => {
const data = await fetchData();
setData(data);
}
useEffect(() => {
settingData();
}, []);
try this one.

Categories