Call api on page load in React - javascript

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>}
);
}

Related

To display the data from postgraphile api into the react app

`
import React, { useEffect, useState } from 'react';
import { useQuery, gql } from '#apollo/client';
import { LOAD_USERS } from "../GraphQL/Queries"
function GetUsers() {
const { error, loading, data } = useQuery(LOAD_USERS);
const [users, setUsers] = useState([]);
useEffect(() => {
if (data) {
console.log(data.allUsers)
setUsers(data.allUsers)
}
}, [data]);
return (
<div>
{users.map((val) => {
return <h1> {val.firstname} </h1>
})}
</div>
)
}
export default GetUsers;
`
the error is occuring in console log as
Uncaught TypeError: users.map is not a function. So please help me with this how do i display it on app. it is being print in the console log

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;

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;

Getting the state with rematch

I am learning rematch/redux. I can't get the state to show with the API.
I have the model imported in index.js along with the store and the provider. These are my reducers/effects:
import { getItems } from './service'
const products = {
state: {
products: [],
},
reducers: {
setProducts(state, products) {
return {
...state,
products,
};
},
},
effects: {
async loadProducts() {
const products = await getItems() // <-- This is the api working normally
this.setProducts(products)
},
}
}
export default products
And this is my component:
import './App.css';
import { connect } from 'react-redux';
import React, { useEffect } from 'react';
const mapStateToProps = ({ products }) => {
return {
...products
}
}
const mapDispatchToProps = ({ products }) => {
return {
...products
}
}
const App = ({ products }) => {
useEffect(() => {
console.log(products)
})
return (
<div className="App">
{console.log(products)}
</div>
)
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
I am not sure what I am missing.
Thank you.
I'm Rematch maintainer, you should review our documentation or consider buying the official Redux made easy with Rematch book where you'll learn all this questions.
I highly recommend using React-Redux hooks instead of connect method.
import './App.css';
import { useSelector, useDispatch } from 'react-redux';
import React, { useEffect } from 'react';
const App = () => {
const dispatch = useDispatch();
const { products } = useSelector(rootState => rootState.products)
useEffect(() => {
dispatch.products.loadProducts();
}, []);
return (
<div className="App">
{console.log(products)}
</div>
)
}
export default App;
Be careful with hooks, you're forgetting to add the deps array to useEffect, any code you add there will run infinitely
Your Rematch models looks fine, you just need to work more on React essentials :)
Redux rematch
Create music listing app using youtube api
How to create folder structure and setup store for react redux
Working code sandbox link
https://codesandbox.io/s/rematch-yf77l0?file=/src/pages/musics/index.jsx

Export JSON object to another .js without class declaration react-native

I am developing a mobile app which makes GET calls using fetch api. I am stuck in that I am trying to export json object( fetched from server with fetch method) to another .js file to be used as array, But when I import my function in another.js (below), it returns nothing. I tested my fetch method with console so it works as expected, however I am unable to process data in another.js file. By the way, I have searched a lot and found this post Helpful, but not worked.
Below code is implementation of fetch part and exporting it.(Products.js)
import React, { PureComponent,Component } from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { productsDataSelector } from "../../Products/ProductsSelectors";
import ProductsList from "../../ProductsList/ProductsList";
import Product from "../../Product/Product";
import { NavigationActions, StackActions } from "react-navigation";
import AnotherComponent from "../../Products/ProductsReducer";
class Products extends PureComponent {
render() {
const { navigation } = this.props;
const { productsData } = this.props;
return (
<View>
<ProductsList list={productsData} isSortable>
{product => <Product product={product} />}
</ProductsList>
</View>
);
}
}
const mapStateToProps = state => ({
productsData: productsDataSelector(state)
});
export const getMoviesFromApiAsync = () =>
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
export default connect(
mapStateToProps,
null
) (Products);
Below code is another.js where importing fetch function and processing returning json object without class declaration implemented.
import React, { Component } from "react";
import {getMoviesFromApiAsyncc} from "../screens/Products/Products";
const fakeData = [];
export const someFunc = () => {
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json())
.then((responseJson) => console.log("responsee:"+JSON.stringify(responseJson)))
.then((responseJson) => {fakeData:JSON.stringify(responseJson)})
.catch((error) => {
console.error(error);
});
};
someFunc();
const initialState = {
data:this.fakeData
};
export default (state = initialState,action) => {
return state;
};
Any recommendations ?? Thanx
I don't see where in your code do you call someFunc and one more thing you need to wrap the object that you return from someFunc in braces otherwise it will be treated as the function's body.
export const someFunc = () => {
getMoviesFromApiAsync().then(response => {
fakeData = JSON.stringify(response)
})
};
someFunc();
I suggest that you move getMoviesFromApiAsync to a separate file and call it from your component to get the list of movies.
api.js
export const getMoviesFromApiAsync = () =>
fetch('http://localhost:8080/JweSecurityExample/rest/security/retrieveItems')
.then((response) => response.json());
product.js
import React, { PureComponent,Component } from "react";
import { connect } from "react-redux";
import { View } from "react-native";
import { productsDataSelector } from "../../Products/ProductsSelectors";
import ProductsList from "../../ProductsList/ProductsList";
import Product from "../../Product/Product";
import { NavigationActions, StackActions } from "react-navigation";
import AnotherComponent from "../../Products/ProductsReducer";
// import getMoviesFromApiAsync
import { getMoviesFromApiAsync } from 'PATH_TO_API.JS'
class Products extends Component {
async componentDidMount(){
const list = await getMoviesFromApiAsync();
console.log(list);
}
render() {
const { navigation } = this.props;
const { productsData } = this.props;
return (
<View>
<ProductsList list={productsData} isSortable>
{product => <Product product={product} />}
</ProductsList>
</View>
);
}
}

Categories