REACT Component to REACT Function - javascript

I have to implement hooks in my Component, but as far as I know it is not possible using the hooks in a REACT.Component.. I am new at REACT and I donĀ“t really have an Idea how I can convert my Component to a function correctly. Can someone show me how to convert the content from my Component to this function?
My Component:
import React from "react";
import { sessionId } from "../common/urlHandler";
import { Settings } from "../settings";
import { Constants } from "../common/constants.js";
import OrderHistoryService from "../services/orderHistory/orderHistoryService";
import OrderHistoryTable from "../orderHistory/orderHistoryTable";
import OrderHistoryPagination from "../orderHistory/orderHistoryPagination";
import OrderHistorySearchField from "../orderHistory/orderHistorySearchField";
export default class OrderHistoryPage extends React.Component {
constructor(props) {
super(props);
const orderHistoryService = new OrderHistoryService(
Settings.baseUrl,
this.props.lang
);
this.state = {
orderHistoryService: orderHistoryService,
sessionId: sessionId(),
orderHistoryData: Constants.DummyOrderHistory,
};
}
componentDidMount() {
//fixMe: fetch-Data and set orderHistoryData
}
render() {
if (this.state.orderHistoryData !== null) {
return (
<section className="section">
<div><OrderHistorySearchField /></div>
<div><OrderHistoryPagination /></div>
<div><OrderHistoryTable orderHistoryData={this.state.orderHistoryData} /></div>
</section>
);
}
}
}
The function into I want to convert my Component:
export default function OrderHistoryPage () {
//fill with data from my Component
}

It should be like this basically you should use useState for states and useEffect for componentDidMount. Also you should remove things that does not exist in functional components like render and this.
import React, {useState, useEffect} from "react";
import { sessionId } from "../common/urlHandler";
import { Settings } from "../settings";
import { Constants } from "../common/constants.js";
import OrderHistoryService from "../services/orderHistory/orderHistoryService";
import OrderHistoryTable from "../orderHistory/orderHistoryTable";
import OrderHistoryPagination from "../orderHistory/orderHistoryPagination";
import OrderHistorySearchField from "../orderHistory/orderHistorySearchField";
export default function OrderHistoryPage (props) {
const orderHistoryService = new OrderHistoryService(
Settings.baseUrl,
props.lang
);
const [orderHistoryService, setorderHistoryService] = useState(orderHistoryService);
const [sessionId, setSessionId] = useState(sessionId());
const [orderHistoryData, setOrderHistoryData] = useState(Constants.DummyOrderHistory);
useEffect(()=> {
//fixMe: fetch-Data and set orderHistoryData
}, []);
return (
{ (orderHistoryData !== null) &&
(<section className="section">
<div><OrderHistorySearchField /></div>
<div><OrderHistoryPagination /></div>
<div><OrderHistoryTable orderHistoryData={this.state.orderHistoryData} /></div>
</section>) }
);
}

Related

Mobx store in react doesn't rerender components

I'm trying to understand mobx. After annotations caused a lot of trouble, I decided to use a global store as described here. My store looks like this:
import {
makeObservable,
observable,
action
} from "mobx";
class Store {
constructor() {
makeObservable(this, {
fetchWorkouts: action,
user: observable,
allWorkouts: observable,
selectedWorkout: observable,
currentStep: observable,
setUser: action
})
}
user = {
uid: null,
email: null,
name: null
}
allWorkouts = []
selectedWorkout = {}
currentStep = 0
fetchWorkouts() {
}
setUser(newUser) {
this.user = newUser;
}
}
const store = new Store()
export default store;
My new user comes directly from the login, which looks like this:
import {Button} from "semantic-ui-react";
import {useHistory} from "react-router-dom"
import React from 'react';
import store from "../../context/Store";
import {toJS} from "mobx";
export default function SubmitLogin(props) {
let history = useHistory();
// eslint-disable-next-line react-hooks/exhaustive-deps
const loginUser = async () => {
let bodyObj = {
email: props.email,
pw: props.password
}
let queryString = "http://localhost:3001/user/login/" + bodyObj.email + "/" + bodyObj.pw;
await fetch(queryString).then(response => response.json()).then(json => store.setUser(json)).then(() => console.log(toJS(store.user))).then(() => history.push("/"));
}
return (
<>
<Button className={"loginRegisterButton"} onClick={loginUser}>Submit</Button>
</>
)
}
To test everything, I am trying to display the uid in my header like this:
import React, {Component} from 'react';
import {Link} from "react-router-dom";
import store from "../context/Store";
class Toolbar extends Component {
render() {
return (
<div id={"toolbarDiv"}>
<p style={{color: "white"}}>{store.user.uid}</p>
</div>
);
}
}
export default Toolbar
However, even after I receive the uid from my server and can print it in my login component, I assume that the data gets correctly assigned to the user variable in the store. Unfortunately, after pressing the sign in button and getting redirected to "/", there is nothing in the toolbar. How can I access the variables correctly?
I think you still need to wrap Toolbar and SubmitLogin in an observer call:
import React, {Component} from 'react';
import {Link} from "react-router-dom";
import { observer } from "react-mobx";
import store from "../context/Store";
class Toolbar extends Component {
render() {
return (
<div id={"toolbarDiv"}>
<p style={{color: "white"}}>{store.user.uid}</p>
</div>
);
}
}
export default observer(Toolbar);
Ref: https://mobx.js.org/react-integration.html

Context empty after async initialisation

I am trying to fetch data from a backend API and initialise my FieldsContext. I am unable to do it, it returns an empty fields array in the Subfields component. I have spent hours on fixing it. But I eventually give up. Please take a look into this. Thanks in advance.
Here is my code
App.js
import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css';
import Index from './components/pages/index/'
import FieldsProvider from './providers/fieldProvider'
import AuthProvider from './providers/authProvider'
import {BrowserRouter as Router,Switch,Route} from 'react-router-dom';
import SubFields from './components/pages/subfields';
function App() {
return (
<Router>
<AuthProvider>
<FieldsProvider>
<Switch>
<Route exact path="/" component={Index} />
<Route exact path="/:fieldid/subfields" component={SubFields} />
</Switch>
</FieldsProvider>
</AuthProvider>
</Router>
);
}
export default App;
FieldsContext.js
import React from 'react'
const FieldsContext = React.createContext();
export default FieldsContext
FieldsProvider.js
import React, { Component } from 'react'
import FieldsContext from '../libs/fieldContext'
export default class FieldsProvider extends Component {
state = {fields:[]}
getFields()
{
fetch('/api/fields')
.then(res => res.json())
.then(fields => this.setState({fields}));
}
async componentDidMount() {
await this.getFields();
}
render() {
return (
<FieldsContext.Provider value={this.state} >
{this.props.children}
</FieldsContext.Provider>
)
}
}
Subfields.js
import React, { Component } from 'react'
import FieldsContext from '../../../libs/fieldContext'
import FieldsList from '../../Fields/fieldlist'
export default class SubFields extends Component {
componentDidMount(){
// const fieldId = this.props.match.params.fieldid;
console.log(this.context);
}
render() {
return (
<div>
</div>
)
}
}
SubFields.contextType = FieldsContext
try using an ES6 Arrow function, which binds the function to the object instance, so that this refers to the object instance of the class when it is called.
When its called asynchronously, this will refer the the class object instance you want to update.
import React, { Component } from 'react'
import FieldsContext from '../libs/fieldContext'
export default class FieldsProvider extends Component {
state = {fields:[]}
// ES6 Arrow function
getFields = () =>
{
fetch('/api/fields')
.then(res => res.json())
.then(fields => this.setState({fields}));
}
async componentDidMount() {
await this.getFields();
}
render() {
return (
<FieldsContext.Provider value={this.state} >
{this.props.children}
</FieldsContext.Provider>
)
}
}
Alternatively, Try binding of your function in the class constructor.
export default class FieldsProvider extends Component {
state = {fields:[]}
constructor(props) {
//bind the class function to this instance
this.getFields = this.getFields.bind(this);
}
//Class function
getFields()
{
fetch('/api/fields')
.then(res => res.json())
.then(fields => this.setState({fields}));
}
async componentDidMount() {
await this.getFields();
}
render() {
return (
<FieldsContext.Provider value={this.state} >
{this.props.children}
</FieldsContext.Provider>
)
}
}
As a side note: Prefer to use functional components for consuming of ContextAPI.
import React, { Component } from 'react'
import FieldsContext from '../../../libs/fieldContext'
import FieldsList from '../../Fields/fieldlist'
export default function SubFields (props) {
const {
match
} = props;
//much better way to consume mulitple Contexts
const { fields } = React.useContext(FieldsContext);
//useEffect with fields dependency
React.useEffect(() => {
console.log(fields);
},[fields]);
return (
<div>
</div>
)
}

my react code is working but when i refresh the page i get TypeError: Cannot read property 'Location' of undefined

Starting with GamePage, it provides 2 routes which renders the components GameList and GameDetailPage. Both work fine at first but When i refresh the page for Gamelist component, it still rerenders the page but when i refresh the page for GameDetailPage, i get the error TypeError: Cannot read property 'Location' of undefined. I do not understand why it is unable to fetch data from state whenever i refresh.
gamepage.jsx
import React from "react";
import GamesList from "../../components/games-list/game-list.component";
import { Route } from "react-router-dom";
import GameDetailPage from "../gamedetailpage/gamedetailpage.component";
import {firestore,convertCollectionsSnapshotToMap} from '../../firebase/firebase.utils'
import {connect} from 'react-redux'
import {updateFootballGames} from '../../redux/games/games.actions'
class GamePage extends React.Component {
unsubscribeFromSnapshot=null;
//whenever the component mounts the state will be updated with the football games.
componentDidMount(){
const {updateFootballGames}=this.props
const gameRef=firestore.collection('footballgames')
gameRef.onSnapshot(async snapshot=>{
const collectionsMap=convertCollectionsSnapshotToMap(snapshot)
updateFootballGames(collectionsMap)
})
}
render() {
const { match } = this.props;
return (
<div className="game-page">
<h1>games page</h1>
<Route exact path={`${match.path}`} component={GamesList} />
<Route path={`${match.path}/:linkUrl`} component={GameDetailPage}
/>
</div>
);
}
}
const mapStateToProps=state=>({
games:state.games.games
})
const mapDispatchToProps=dispatch=>({
updateFootballGames:collectionsMap=>
dispatch(updateFootballGames(collectionsMap))
})
export default connect(mapStateToProps, mapDispatchToProps)(GamePage);
gamedetailpage.component.jsx
import React from "react";
import { connect } from "react-redux";
import GamePreview from '../../components/game-preview/game-preview.component'
import GameDetails from '../../components/game-details/game-details.component'
const GameDetailPage = (props) => {
const {games, match} = props
const urlparam =match.params.linkUrl
// const games_array = Object.entries(games)
const gameObj=games[urlparam]
console.log('prop',gameObj)
return (
<div className="game-list">
<GameDetails game = {gameObj}/>
</div>
);
};
const mapStateToProps = (state) => ({
games: state.games.games,
});
export default connect(mapStateToProps)(GameDetailPage);
game_details.component.jsx
import React from 'react';
const GameDetails = (props) => {
console.log(props.game.Location)
return(
<div>
Location:{props.game.Location}
<br/>
Price:{props.game.Price}
</div>
)
}
export default GameDetails;
gamelist.component.jsx
import React from "react";
import './game-list.styles.scss'
import GamePreview from "../game-preview/game-preview.component";
import {connect} from 'react-redux'
const GameList=(props)=>{
const {games}=props
console.log(games)
const game_list=Object.entries(games)
console.log(game_list)
return (
<div className="game-list">
{game_list.map(game =>
<GamePreview game = {game[1]}/>)}
</div>
);
}
const mapStateToProps=state=>({
games:state.games.games
})
export default connect(mapStateToProps)(GameList);
gamepreview.component.jsx
import React from "react";
import "./game-preview.styles.scss";
import { withRouter, Route } from "react-router-dom";
import GamePreviewDetail from "../game-preview-detail/game-preview-detail.component";
const GamePreview = (props) => {
const { Location, Time, linkUrl, Price } = props.game;
const { history, match } = props;
return (
<div
className="game-preview"
onClick={() => history.push(`${match.url}/${linkUrl}`)}
>
<div className="game-preview-image">
<p>Picture goes here</p>
</div>
{/* <GamePreviewDetail name = {Location} price={Price}/> */}
<p>Location:{Location}</p>
<p>Price:{Price}</p>
</div>
);
};
export default withRouter(GamePreview);
app.js
import React from 'react';
import './App.css';
//import dependencies
import { Route, Switch } from "react-router-dom";
//import pages
import HomePage from './pages/homepage/homepage'
import GamesPage from './pages/gamespage/gamespage'
import SignInSignUp from './pages/signin-signup-page/signin-signup-page'
import GameDetailPage from "./pages/gamedetailpage/gamedetailpage.component";
import Header from './components/header/header.component';
import { auth, createUserProfileDocument } from './firebase/firebase.utils';
class App extends React.Component{
constructor() {
super();
this.state = {
currentUser: null
}
}
unsubscribeFromAuth = null
componentDidMount() {
this.unsubscribeFromAuth = auth.onAuthStateChanged(async userAuth => {
if (userAuth) {
const userRef = await createUserProfileDocument(userAuth);
// check if the snapshot has changed (subscribe)
// get the user that we just created or that already exists in the db
userRef.onSnapshot(snapshot => {
this.setState({
currentUser: {
id: snapshot.id,
...snapshot.data()}
})
})
} else {
this.setState({currentUser: userAuth})
}
})
}
componentWillUnmount() {
this.unsubscribeFromAuth();
}
render(){
return(
<div>
<Header currentUser = {this.state.currentUser}/>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/games" component={GamesPage} />
<Route exact path="/signin" component={SignInSignUp} />
</Switch>
</div>
)
}
}
export default App;
I would try using useParams hook instead. Then capturing any changes of linkUrl with useEffect hook. Also introducing gameObj with useState.
useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current <Route>.
If you're familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
Try to modify <GameDetailPage /> component as the following:
import React, { useState, useEffect } from 'react';
import { useParams } from "react-router-dom";
// other imports
const GameDetailPage = (props) => {
const { games } = props;
let { linkUrl } = useParams();
const [ gameObj, setGameObj ] = useState(null);
useEffect(() => {
if (games) {
const newGameObj = games[linkUrl];
console.log('game object', newGameObj);
setGameObj(newGameObj);
}
}, [games, linkUrl]);
return <div className="game-list">
{ gameObj && <GameDetails game={ gameObj } /> }
</div>
}
+1 - null check:
Also you can see a null check in the return statement for gameObj which helps rendering only that case once you have a value in games array with found linkUrl value.
I hope this helps!

How to test a react component with props?

I need to test a react components with props mounts ok and renders its content such as paras and divs correctly. My code can be found below or in this sandbox
I tried testing it with a default prop but that didn't work.
import React from 'react';
import test from 'tape';
import {mount} from 'enzyme';
test('testing', t => {
t.doesNotThrow(() => {
wrapper = mount(<App2 txt={ok}/>);
}, 'Should mount');
t.end();
});
And this is my component with props.
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App from './index'
export default class App2 extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
const {txt}=this.props
return (
<div>
<p>hi {txt}</p>
</div>
);
}
}
And the outer component supplying the prop.
import React, { Component } from 'react';
import { render } from 'react-dom';
import Hello from './Hello';
import './style.css';
import App2 from './app2'
class App extends Component {
constructor() {
super();
this.state = {
name: 'React'
};
}
render() {
return (
<div>
<Hello name={this.state.name} />
<p>
Start editing to see some magic happen :)
</p>
<App2 txt={this.state.name}/>
</div>
);
}
}
render(<App />, document.getElementById('root'));
So you would do something like providing the properties yourself and ensuring that it renders with them:
test('test your component', () => {
const wrapper = mount(<App2 txt={'michaelangelo'} />);
expect(wrapper.find('p').text()).toEqual('hi michaelangelo');
});
You shouldn't worry about testing the and html elements like that, but rather the props that you pass and that they render in the right place i.e., in the p tag

Pass data from react component

I have a GetData.js component that gets API data and sets it to an array. I want to access that array data in multiple other components and manipulate it in multiple different ways.
For example, I want to be able to do something like this:
import APIdata from './GetData';
var data = APIdata.object;
var result = [];
if (data) {
for (var i = 0; i < data.length; i++) {
if (data.form_values["6f71"] === "KeyWord") {
result.push(data)
}
}
}
You're looking at a fairly straightforward use of container components, props, and state.
Here's a contrived example:
import React, {Component} from 'react';
import OtherComponent1 from './OtherComponent1';
import OtherComponent2 from './OtherComponent2';
class GetDataComponent extends Component {
constructor() {
super(props);
this.state = {
data: []
}
}
fetchMyData() {
const resultingArray = ...
this.setState({data: resultingArray});
}
componentDidMount() {
this.fetchMyData();
}
render() {
return (
<div>
<OtherComponent1 someArrayProp={this.state.data}/>
<OtherComponent2 differentArrayProp={this.state.data}/>
</div>
);
}
}
export default App;
import React, {Component} from 'react';
import PropTypes from 'prop-types';
class OtherComponent1 extends Component {
render() {
return (
<div>
The someArrayProp: {this.props.someArrayProp}
</div>
);
}
}
OtherComponent1.propTypes = {
someArrayProp: PropTypes.array;
}
export default App;
import React, {Component} from 'react';
import PropTypes from 'prop-types';
const OtherComponent2 = (props) => (
<div>
The differentArrayProp: {props.differentArrayProp}
</div>
);
OtherComponent2.propTypes = {
differentArrayProp: PropTypes.array;
}
export default App;

Categories