Why does it make a mistake? - javascript

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;

Related

why am I getting an error in fetching data here?

I have this for saving fetched data in state:
import React, {useState, useEffect, createContext} from 'react';
import { getLocation } from '../api';
export const LocationContext = createContext();
const LocatonContextProvider = (props) => {
const [location, setLocation] = useState({})
useEffect(() => {
const fetchAPI = async () => {
setLocation(await getLocation());
}
fetchAPI();
}, [])
return (
<LocationContext.Provider value={location}>
{props.children}
</LocationContext.Provider>
);
};
export default LocatonContextProvider;
and this for saving weather data
import React, {useState, useEffect, createContext, useContext} from
'react';
//api
import { getWeather } from '../services/api';
//Context
import { LocationContext } from '../contexts/LocationContextProvider';
export const WeatherContext = createContext()
const WeatherContextProvider = ({children}) => {
const location = useContext(LocationContext);
const lat = location.lat;
const lon = location.lon;
const [weather, setWeather] = useState({});
useEffect(() => {
const fetchAPI = async () => {
setWeather(await getWeather(lat,lon));
}
fetchAPI();
}, [lat, lon])
return (
<WeatherContext.Provider value={weather}>
{children}
</WeatherContext.Provider>
);
};
export default WeatherContextProvider;
and here is the axios request:
import axios from "axios";
const getLocation = async () => {
const LOCATION_URL = 'http://ip-api.com/json/?fields=country,city,lat,lon,timezone';
const response = await axios.get(LOCATION_URL);
return response.data;
}
const getWeather = async (lat, lon) => {
const WEATHER_URL = `https://api.openweathermap.org/data/2.5/weather?
lat=${lat}&lon=${lon}&appid=bac9f71264248603c36f011a991ec5f6`;
const response = await axios.get(WEATHER_URL)
return response.data;
}
export {getLocation, getWeather};
When I refresh the page, I get an 400 error and after that I get the data, I don't know why the error occurs
useEffect(() => {
const fetchAPI = async () => {
setWeather(await getWeather(lat,lon));
}
if (lat && lon) {
fetchAPI();
}
}, [lat, lon])

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

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;

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;

Getting error when calling an action from container in react-redux

I am integrating redux with my react-native app. I have moved my state and action management to Container and integrated the container with component using 'connect'.
App.js
const AppNavigator = createSwitchNavigator({
SplashScreen: SplashScreen,
render() {
return(
<Provider store={store}>
<AppNavigator/>
</Provider>
)
}
});
const store = createStore(reducer);
export default createAppContainer(AppNavigator);
SignIn.js
import React from "react";
import {View} from "react-native";
import authenticateUser from "../../../services/api/authenticateUser";
const SignIn = (props) => {
const authenticate = async () => {
try {
return await authenticateUser.get('/abc', {
params: {
code,
}
});
}
catch (e) {
}
}
const validateUserCredentials = (isValid) => {
authenticate().then(response => {
const responseData = response.data;
props.updateEventRules(responseData);
});
}
}
return (
<View></View>
);
export default SignIn;
Sign-InContainer.js
import {eventRulesUpdated} from '../../../actions/actions';
import {connect} from 'react-redux';
import SignIn from './signin-screen';
const mapStateToProps = (state) => ({});
const mapDispatchToProps = dispatch => {
return {
updateEventRules: rules => {
dispatch(eventRulesUpdated(rules))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);
When running the app I am getting an error that - props.updateEventRules() is not a function.
Can anyone please help me what am I doing wrong?
You should have the connect functions inside Signin.js like this
import React from "react";
import {View} from "react-native";
import authenticateUser from "../../../services/api/authenticateUser";
const SignIn = (props) => {
const authenticate = async () => {
try {
return await authenticateUser.get('/abc', {
params: {
code,
}
});
}
catch (e) {
}
}
const validateUserCredentials = (isValid) => {
authenticate().then(response => {
const responseData = response.data;
props.updateEventRules(responseData);
});
}
}
return (
<View></View>
);
const mapStateToProps = (state) => ({});
const mapDispatchToProps = dispatch => {
return {
updateEventRules: rules => {
dispatch(eventRulesUpdated(rules))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SignIn);

Categories