Export function from React Class - javascript

I am trying to implement a dapp using react js.In my app.js inside the app class, there is a method that I want to export to another module.I tried many options,but none of them worked for me. In the below code, I want to export username().
App.js Code
export default class SessionStore
{
......
username ()
{
if (!this._user || !this._user.username) return null
return this._user.username
}
......
}
How to import and use username() function to another modules. I am new to reactjs, so please help me to resolve this issue.

You can make the method static, but can't access props or state in the method. Better write a util function, which accepts user as argument and import in both classes.
utils.js
export const getUserName = (user = {}) => user.username ? user.username : null;
App.js
import { getUserName } from '../utils';
export default class SessionStore {
......
username = () => getUserName(this._user);
......
}

Related

How to implement Broadcast Channel API in React

I need to check when the user opens a new tab if there any other tabs are opened in the browser. So when we can able to find that there are no tabs opened already, then we need to do some operations if not we can just leave
How can we achieve this using Broadcast Channel API?
Especially how to implement this concept in React?
Thanks in Advance!!
I will answer the second part of your question "Especially how to implement this concept in React?"
I will give an example of implementing multi-tab logout.
Create a file somewhere in your App , I created mine in a folder called Auth and created a file named auth.js
import { BroadcastChannel } from 'broadcast-channel';
const logoutChannel = new BroadcastChannel('logout');
export const login = () => {
localStorage.setItem("token", "this_is_a_demo_token")
history.push('/app/dashboard')
}
export const logout = () => {
logoutChannel.postMessage("Logout")
localStorage.removeItem("token", 'this_is_a_demo_token' )
window.location.href = window.location.origin + "/";
}
export const logoutAllTabs = () => {
logoutChannel.onmessage = () => {
logout();
logoutChannel.close();
}
}
As you can see, I use this dependency npm i broadcast-channel for simplicity with my React App.
Create an instance called logoutChannel with the name 'logout'. On logging out , the instance sends a post message ('Logout').
Use the logoutAllTabs function in your App.js file as follows
import React, { useEffect } from "react";
import { logoutAllTabs } from "./auth/auth";
import Router from "./routes";
function App() {
useEffect(() => {
logoutAllTabs()
}, [])
return (
<>
<Router/> // All routes here
</>
);
}
export default App;
Kindly follow this tutorials to see the above implementation in action :
1.) https://youtu.be/mb5nuUbvfvM
2.) https://dev.to/demawo/how-to-logout-of-multiple-tabs-react-web-app-2egf

Get function inside default export function

I have function inside user.js with default export like this
export default {
var getListFriends = async (accessToken) =>{
}
....other function
return {
getListFriends,
...other function...
}
}
then I import it to index.js
import userService from './user';
Then I will add only index.js to plugin.
I can call this.$userService (it shows as anonymous function) but this.$userService.getListFriends return undefined.
How can I call function getListFriends from import.
Thank you very much.
where is user.js?
if its inside plugins directory, you have to use inject to add it to your nuxt.
then you can access it via nuxt object inside your code.
see this example from nuxt docs:
export default ({ app }, inject) => {
// Inject $hello(msg) in Vue, context and store.
inject('hello', msg => console.log(`Hello ${msg}!`))
}
you can see the full document here
ok now for this to work the way you want you need to change your user.js file,
export default {
friends: () => {
console.log('hi bro');
},
notFriends: () => {
console.log('go away man im not your bro');
}
};
something like this.
you dont need inject or app in your user.js.
and your code problem is that you are defining a function and trying to access it's inner values from the outside like:
function boo() {
var b = 0;
}
you can not access the value of b with boo.b. its a local variable to the boo function
instead create a object and have multiple functions inside your object

How do I use "then" with TypeScript?

I'm converting a React app from pure JS to TypeScript. It's linked to firebase; the firebase functions are in a separate file. The one I'm currently working on is to allow the user to change their password. I have a form which accepts the new password and saves it (there's also some validation, but I've left that out). In pure js, it all works fine, but when I convert to TypeScript I'm getting stuck on what to do with the "then" part.
So far my js files are as follows.
PasswordForm.js (so this was originally a js file, which I've changed to tsx; I've added a couple of interfaces and used them, but that's all I've changed):
import React, {useState} from 'react';
import { withFirebase } from '../Firebase';
interface FormProps {
firebase: {
doPasswordUpdate: (string) => void // Not sure about this line
}
}
interface FormState {
password: string
}
const INITIAL_STATE: FormState = {
password: ""
};
const ChangePasswordForm = ({ firebase }: FormProps) => {
const [formValues, setFormValues] = useState(INITIAL_STATE);
const handleSubmit = event => {
firebase
.doPasswordUpdate(formValues.password)
.then(() => { // THIS IS WHERE THE PROBLEM HAPPENS
... do other things ...
})
.catch(error => {...});
};
return (
<form
onSubmit={handleSubmit}>
<input
name="password"
value={formValues.password}
/>
<button type="submit">Submit</button>
</form>
);
export default withFirebase(ChangePasswordForm);
My firebase functions are wrapped in a Context, but the actual functions are in firebase.js (I haven't done anything to convert this to TypeScript):
import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/database';
const config = {...}; // Firebase keys etc
class Firebase {
constructor() {
app.initializeApp(config);
this.auth = app.auth();
this.db = app.database();
}
doPasswordUpdate = password =>
this.auth.currentUser.updatePassword(password);
}
export default Firebase;
The error I get (in VSCode) is:
Property 'then' does not exist on type 'void'.
Presumably this is because I've said that doPasswordUpdate should return void, which obviously doesn't have a "then" property. But what should I use instead of void? Is there something that does have a "then"? Or is there another way to do this?
The problem is that you are telling TypeScript lies about your firebase object.
interface FormProps {
firebase: {
doPasswordUpdate: (string) => void // Not sure about this line
}
}
Explicitly tells the code that doPasswordUpdate does not have a return value.
Instead, you should just use your class's declaration by importing it and then using it.
// import the class declaration
import Firebase, { withFirebase } from '../Firebase';
interface FormProps {
// tell the compiler that your firebase is a Firebase
firebase: Firebase
}
This way, the compiler knows to look at your Firebase class for the type information regarding doPasswordUpdate.
In VSCode you can press CTRL, move your cursor over updatePassword and see the function's definition. Use return type instead of void in your function.

Error in cypress object model : Cannot find module '../ObjectModel/LoginPage'

I tried to write object model in vscode, to create an object.
This is login2 :
/// <reference types="Cypress" />
import LoginPage from "../../integration/ObjectModel/LoginPage"
describe('home page', () => {
it('loginPage', function () {
const lp = new LoginPage()
})
})
This is object page :
class LoginPage {
visit(){
cy.visit('https://facebook.com');
}
fillEmail(value){
const feild = cy.get('#email')
feild.clear()
feild.type(value)
return this
}
fillPassword(value){
const feild = cy.get('#pass')
feild.clear()
feild.type(value)
return this
}
submit(){
const button = cy.get('#u_0_b')
button.click()
}
}
export default LoginPage;
This is the path of files:
and this the error
How I can solve it?
I tried to change the path as I read, also it does not solved.
Seems like the file login2.js is in the same directory as ObjectModel. Thus you only need to import file like this:
import LoginPage from "./ObjectModel/LoginPage"
You are trying to use the import/export, which is newer/modern version to module.exports and it works only when you install babel and setup the babel configuration to transform the modules in order to work with import/export. Please try to replace export default LoginPage with module.exports = new LoginPage(); in the page class.
const LoginPage = require("../../integration/ObjectModel/LoginPage")
And in your it/test, you don't need to say const lp = new LoginPage() as you are importing the page on top with require
the problem solved by changing the path to
import LoginPage from "./ObjectModel/LoginPage"

TypeError: Webpack imported module is not a function

I have a backend that calculates work shifts.
I am trying to post some required user input with a module in services/shifts.
The getAll method works fine, but posting throws an error
TypeError: _services_shifts__WEBPACK_IMPORTED_MODULE_2__.default.postData is not a function
Shiftservice module:
import axios from 'axios'
const baseUrl = '...'
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const postData = newObject => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
export default {getAll, postData}
I have a button that triggers the following calling code on click:
import shiftService from './services/shifts'
const postData = (event) => {
event.preventDefault()
const sampleObject = {
sampleField: sample
}
shiftService
.postData(sampleObject)
.then(returnedData => {
console.log(returnedData)
})
}
When execution reaches shiftService.postData, the error is thrown.
I am really confused since I am basically copying some older project of mine which works, but here I just don't find the problem. Thank you in advance for helping a newcomer!
Modules provide special export default (“the default export”) syntax to make the “one thing per module” way look better.There may be only one export default per file.And we may neglect the name of the class in the following example.
//Module1
export default class{
}
And then import it without curly braces with any name:
//Module2
import anyname from './Module1'
Your scenario is different having two functions.You can either export default one function
export default getAll
and normal export the other function.
export postData
and when importing
import{ default as getAll,postData} from './yourModule'
OR
Remove default here in Shiftservice module and export normally:
import axios from 'axios'
const baseUrl = '...'
const getAll = () => {
const request = axios.get(baseUrl)
return request.then(response => response.data)
}
const postData = newObject => {
const request = axios.post(baseUrl, newObject)
return request.then(response => response.data)
}
export {getAll, postData}
Importing in your module
import {getAll,PostData} from './Module1'
or
import * as shiftService from './Module1'
and then use shiftServer.postData().....
Okay, I am embarrassed of the solution. I was just editing an earlier version of shiftService from a wrong folder, and the imported service only had the get method in it...
So my code actually works if placed correctly. Thank you for your time, and thanks for sharing alternative ways that must work aswell.
I think its becuse your declaring the function as arrow functions
and export it this way:
export default {getAll, postData}
you need to declare them as a normal functions
function postData(){
}
that should work

Categories

Resources