Simply what im trying to do is export a function that make a mongodb query and import it into a react component so i can call it there and display the data.
this is the error i keep getting: ./node_modules/require_optional/node_modules/resolve-from/index.js
Module not found: Can't resolve 'module' in '/Users/paul/Desktop/TempProject/Dietx/dietxweb/node_modules/require_optional/node_modules/resolve-from'
react component, Diet.js:
import React, {Component} from 'react';
import getItemList from '../server/api.js';
import ReactList from 'react-list';
class Diet extends Component {
constructor(props){
super(props)
this.state ={
Calories : 3000,
Items: [],
}
}
componentWillMount(){
}
render(){
return(
<div className="diet-container">
<p>lol</p>
</div>
)
}
}
export default Diet;
API, api.js:
const mongo = require('mongodb');
export const getItemList = ()=>{
var url = "mongodb://localhost:27017/food"
return(
mongo.connect(url)
.then((db)=>{
return db.collection('foodInfo')
})
.then((res)=>{
return res.find().toArray()
})
)
}
Change
export const getItemList = ()=>{
to
export default function getItemList() {
The syntax you are using is importing the default member from the module but your module does not define a default member.
Alternatively, you could use the syntax
import {getItemList} from ...
Related
I need to get data from Firestore but i can't, i need to know if my code is ok, because it doesn't work or something else is missing.
This is my firestore services
fireservices.js
import React from 'react';
import * as firebase from 'firebase';
import { firebaseConfig } from '../firebase_const';
import 'firebase/firestore';
firebase.initializeApp(firebaseConfig)
class FireServices{
static async getLocalization(idOfert) {
firebase.firestore.collection('users').doc(idOfert)
}
}
export default FireServices;
And this is my class, this class use the method to get data
SecondClass.js
import React from 'react';
import FireServices from '../services/fireservices';
export default class SecondClass extends React.Component {
componentDidMount = async () => {
this.onStart()
}
onStart = () => {
FireServices.getLocalization('email#hotmail.com').get().then(doc => {
console.log(doc)
})
}
render(){
return (
<View>
</View>
)
}
You are not returning from getLocalization.
It should be
static async getLocalization(idOfert) {
return firebase.firestore.collection('users').doc(idOfert)
}
I'm trying to export a component without the decorators (connect() in this case)
for unit testing with jest.
So, how could I do this:
import React, { Component } from 'react';
import { connect } from 'react-redux';
export class Header extends Component {
render(){
return <pre>Header</pre>
}
}
export default connect()(Header);
With this component (the export at the beginning doesn't work, it stills exports the connected component)
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
Header = connect()(Header);
export default Header;
Use different variable for your connected component as the following code:
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
let HeaderConnected = connect()(Header);
export default HeaderConnected;
Now you can import your Header freely without using connect()
This can be done without even changing default export:
export let Header = props => {
render(){
return <pre>Header</pre>
}
}
export default connect()(Header);
There may be no need to export original component for connect alone because most well-designed HOCs expose original component:
import Header from '...';
const OriginalHeader = Header.WrappedComponent;
I am trying to pass a value from a context provider to a consumer using useContext and access the value outside of the render function.
My provider looks like so:
export const AppContext = React.createContext();
export class App extends React.Component(){
render(){
<AppContext.Provider value={{ name: 'John' }} ><Main /></AppContext>
}
}
My consumer looks like so
import React, { useContext } from 'react';
import { AppContext } from './App';
export class Main extends React.Component(){
componentDidMount(){
const value = useContext(AppContext);
}
render(){
return (
<div>Main Component</div>
)
}
}
The error is this:
Invalid hook call. Hooks can only be called inside of the body of a function component.
If you want to use hooks they are designed for function components. Like so:
import React, { useContext } from 'react';
import { AppContext } from './App';
const Main = () => {
const value = useContext(AppContext);
return(
<div>Main Component</div>
);
}
If you want to use it in a class based component then just set it as a static contextType in your class and then you can use it with this.context in your component like so:
import React from 'react';
import { AppContext } from './App';
class Main extends React.Component(){
static contextType = AppContext;
componentDidMount(){
const value = this.context;
}
render(){
return (
<div>Main Component</div>
)
}
}
Edit:
Remove your context from your app component and place it in its own component. I think you are receiving conflicts in your exporting of your context.
so your app component should look like:
import React from "react";
import Context from "./Context";
import Main from "./Main";
class App extends React.Component {
render() {
return (
<Context>
<Main />
</Context>
);
}
}
export default App;
Your main component should be like:
import React from "react";
import { AppContext } from "./Context";
class Main extends React.Component {
static contextType = AppContext;
render() {
return <div>{this.context.name}</div>;
}
}
export default Main;
and your context component should be like:
import React from "react";
export const AppContext = React.createContext();
class Context extends React.Component {
state = {
name: "John"
};
//Now you can place all of your logic here
//instead of cluttering your app component
//using this components state as your context value
//allows you to easily write funcitons to change
//your context just using the native setState
//you can also place functions in your context value
//to call from anywhere in your app
render() {
return (
<AppContext.Provider value={this.state}>
{this.props.children}
</AppContext.Provider>
);
}
}
export default Context;
Here is a sandbox to show you it working CodSandbox
You get the above error because Hooks are meant to be used inside functional components and not class component whereas you try to use it within componentDidMount of Main component which is a class component
You can rewrite your code for Main component using useContext hook like
import React, { useContext } from 'react';
import { AppContext } from './App';
export const Main =() =>{
const value = useContext(AppContext);
return (
<div>Main Component</div>
)
}
or use Context in a different way with class like
import React from 'react';
import { AppContext } from './App';
class Main extends React.Component {
componentDidMount(){
const value = this.context;
// use value here. Also if you want to use context elsewhere in class
// you can use if from this.context
}
render(){
return (
<div>Main Component</div>
)
}
}
Main.contextType = AppContext;
export { Main };
Hooks only work with stateless components. You are trying to use it in class component.
Here is the content for Main.js file. Uncomment the commented part if you want to use class-based component instead of the functional one.
import React from "react";
import { AppContext } from "./App";
/** UNCOMMENT TO USE REACT CLASS COMPONENT */
// class Main extends React.Component() {
// render() {
// return (
// <AppContext.Consumer>
// {value => <div>It's Main component. Context value is ${value.name}</div>}
// </AppContext.Consumer>
// );
// }
// }
const Main = () => {
const value = React.useContext(AppContext);
return <div>It's Main component. Context value is ${value.name}</div>;
};
export default Main;
Here is the content for App.js file. Uncomment the commented part if you want to use class-based component instead of the functional one.
import React from "react";
import ReactDOM from "react-dom";
import Main from "./Main";
export const AppContext = React.createContext();
/** UNCOMMENT TO USE REACT CLASS COMPONENT */
// export class App extends React.Component() {
// render() {
// return (
// <AppContext.Provider value={{ name: "John" }}>
// <Main />
// </AppContext.Provider>
// );
// }
// }
const App = () => (
<AppContext.Provider value={{ name: "John" }}>
<Main />
</AppContext.Provider>
);
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
React Hooks were implemented directly for the functional components in order to give them the possibility to become stateful. Class-based components were stateful all the time, so you have to use their own state API.
Working demo is available here.
I'm trying to work with MobX for a new project.
I started it on May 2017, and everything was working well. I had to stop, and now I go on developing it. I had to make an npm install to manage making it working, but now, I have some problem with stores...
I rely on this tutorial for the structure : https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb
This is my structure :
Main index.js
import { Provider } from 'mobx-react';
import Stack from './router';
import stores from './stores';
export default class App extends Component {
render() {
return (
<Provider {...stores}>
<Stack />
</Provider>
);
}
}
Index.js of my stores in ./stores/index.js
import ChatStore from './ChatStore';
import UserStore from './UserStore';
export default {
UserStore: new UserStore(),
ChatStore: new ChatStore(),
};
./stores/UserStore.js (important parts)
import { observer, inject } from 'mobx-react';
import {autobind} from 'core-decorators';
...
#inject(['ChatStore'])
#observer
#autobind
export default class UserStore {
#observable isAuthenticated = false;
#observable isConnecting = false;
#observable user = null;
#observable messages = [];
#observable hasMoreMessages = false;
#observable skip = 0;
...
login() {
const payload = {
strategy: 'local',
material_id: DeviceInfo.getManufacturer(),
password: DeviceInfo.getManufacturer()
};
return this.authenticate(payload);
}
...
Now, for components part :
Router.js
import { StackNavigator } from 'react-navigation';
import Home from './containers/Home';
const stackNavigatorConfig = {
initialRouteName: 'Home',
};
export default StackNavigator({
Home: {
screen: Home,
},
}, stackNavigatorConfig);
./containers/Home.js
import React, { Component } from 'react';
import { AsyncStorage } from 'react-native';
import { observable } from 'mobx';
import { observer, inject } from 'mobx-react';
#inject('UserStore')
#observer
export default class Home extends Component {
props: Props;
...
render() {
this.props.UserStore.login().catch(error => {
console.log('LOGIN', 'ERROR', JSON.stringify(error), error.message);
});
return {
...
}
}
And then, I get an error :
So, I sum up :
I use <Provider> from MobX, to give all my stores to my app
Then, I get the Store I want in my component with #inject
I use it as a props, using this.props.UserStore...
But it does not work. I rely on this tutorial for the structure : https://blog.callstack.io/write-react-native-apps-in-2017-style-with-mobx-e2dffc209fcb
Maybe there was an update between May 2017 and today, that makes things different... It was working well on May 2017.
I think this is a dummy error, but I can't find which one...
Everything looks good except the decorators on your UserStore class: #inject(['ChatStore']) #observer #autobind. #inject(['ChatStore']) #observer is used on React components, #autobind might still work as intended.
It should work if you remove those.
maybe worth using #action from mobx
I started getting this error when I added the channels array as a way to mock a list of channels in the beginning phases of my application.
index.js:7852 Uncaught ReferenceError: channels is not defined(…)
Here is the App.js file:
import React from 'react';
import ReactDOM from 'react-dom';
let channels = [
{name: 'Hardware Support'},
{name: 'Software Support'}
];
class Channel extends React.Component {
onClick(){
console.log('I was clicked', this.props.name);
}
render(){
return (
<li onClick={this.onClick.bind(this)}>{this.props.name}</li>
)
}
}
export default Channel
Here is the main.js file:
import React from 'react';
import ReactDOM from 'react-dom';
import Channel from './App';
class ChannelList extends React.Component {
render(){
return (
<ul>
{this.props.channels.map(channel => {
return (
<Channel name={channel.name} />
)
}
)}
</ul>
)
}
}
class ChannelForm extends React.Component{
onChange(e){
console.log(e.target.value);
}
onSubmit(e){
}
render(){
return (
<form onSubmit={this.onSubmit.bind(this)}>
<input type='text' onChange={this.onChange.bind(this)} />
</form>
)
}
}
class ChannelSection extends React.Component {
render(){
return(
<div>
<ChannelList channels={channels}/>
<ChannelForm />
</div>
);
}
}
ReactDOM.render(<ChannelSection />, document.getElementById('app'));
As mentioned by #FelixKling, the channels variable isn't available to your main.js file, as it's not being exported from App.js. The simplest way to share this across both files would be to export is as a non-default export, then pull it in as part of your Channels import in Main.js
Like so:
// App.js
let channels = [
{name: 'Hardware Support'},
{name: 'Software Support'}
];
...
export channels; // this is the variable export
export default Channel; // this is the class export, which will be the default if no specific export is declared in your import
// Main.js
import Channel, { channels } from './App';
// `Channel` class is imported as usual, along with non-default `channels` export
You should also use const instead of let in your channels declaration, as you're not reassigning it.
const channels = ...