Vue extend a class that has an import - javascript

I've defined an import on a component. I then have another component that extends off of it. How would I go about defining and accessing the Service that the parent component has imported?
Service
export default {
getSomeData() {
return [1,2,3,4]
}
}
Parent Component
import Service from '../service';
export default {
data() {
return {
testData: 'test'
}
}
}
Child Component
import Component from '../component';
export default {
extends: Component,
mounted() {
console.log(Service.getSomeData()); // [1,2,3,4] Doesn't work, Service not defined.
console.log(this.testData); // 'test' Works
}
}
Generally I would just import Service in the child component and use that function. How do I define it in the parent so that I can access it in the child without having to import it again for other children? I would prefer not to make it into a Vue component and extend it.
Thanks

You can assign it to a data property:
import Service from '../service';
export default {
data() {
return {
testData: 'test',
service: Service
}
}
}
import Component from '../component';
export default {
extends: Component,
mounted() {
console.log(this.service.getSomeData()); // [1,2,3,4]
console.log(this.testData); // 'test' Works
}
}

Related

How we can share state object to another react file

in the first react file i called an api to get some data and save it in this.state.Data
import React, { Component } from "react";
import axios from "axios";
import Layout from "./Layout";
class Db extends Component {
constructor() {
super();
this.state = {
Data: [],
};
}
componentDidMount() {
axios.get(`https://breakingbadapi.com/api/characters`).then((res) => {
const data = res.data;
this.setState({ Data: data });
});
}
render() {
return <h1>DB working</h1>;
}
}
export default Db;
in the another react file i need to get this.props.Data from Db.js file but i dont know how to get it
import React, { Component } from "react";
import Db from "./Db";
class Filler extends Component {
constructor() {
super();
}
render() {
return <div></div>;
}
}
export default Filler;
for small projects you can use React ContextApi to save states in global level and use it inside components you want.
for big projects you can use state management libraries like Redux. it's too much for small projects.

'How to acccess data property inside setup in vue 3?

I am trying to access data property inside setup() in vue 3 but is giving me this error
TypeError: Cannot read property '$localStorage' of undefined
data()
data() {
return {
$localStorage: {},
}
setup
setup() {
this.$localStorage
}
How i can access this property inside setup()?
One solution would be importing getCurrentInstance from vue and use it in onMounted lifecycle or in a consumable:
import { onMounted, getCurrentInstance } from "vue";
export default {
data() {
return {
key: "test",
};
},
setup() {
onMounted(() => {
console.log(getCurrentInstance().data.key);
});
},
};
However, this usage is highly discouraged as stated in here.
Instead you could define that data property in setup using ref or reactive like this:
import { ref } from "vue";
export default {
setup() {
const $localStorage = ref({});
},
};
or
import { reactive } from "vue";
export default {
setup() {
const $localStorage = reactive({});
},
};
These solutions will work if your data and setup function will be in the same component.
If you are trying to access to a child component, you can use ref for accomplishing this task. More detailed information about ref is here

Not getting props from child component in Redux

I want to get props from Redux in the child component. But {this.props} is empty object. I am using react-redux connect to get the props. It is working in parent component and we can pass to child component to get the props but I need to get from child component
Login
```import React, { Component } from 'react'
import { Test } from './Test'
export default class Login extends Component {
render() {
return (
<div>
<Test hi=""/>
</div>
)
}
}```
Test
import React, { Component } from 'react'
import { connect } from 'react-redux'
export class Test extends Component {
render() {
console.log(this.props)
return (
<div>
vddfff
</div>
)
}
}
const mapStateToProps = (state) => ({
})
const mapDispatchToProps = (dispatch) => {
return {
selectedData: (val) => {
console.log("object")
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)
The problem here is that you are trying to use the Test component you wrote instead of the Higher order component which is being returned by the connect() from react-redux
You don't need to export the Test class.
In login.js file, use
import Test from './Test'
instead of
import {Test} from './Test'
See it in action here.
https://codesandbox.io/s/sample-test-app-q5srf
You used the wrong component. In login you need to import:
import Test from './Test'
You imported Test wich is not connected to redux (that pushes the redux props).

Vue.js asyncronous components, named import

I know how to load asynchronous component in Vue. This
import MyComponent from '#/components/MyComponent'
export default {
components: {
MyComponent
}
}
is replaced like
export default {
components: {
MyComponent: () => import('#/components/MyComponent')
}
}
But how can I replace "named" component import, like this?
import { SweetModal } from 'sweet-modal-vue'
export default {
components: {
SweetModal
}
}
How do I import that asynchronously?
You could use at the same way, but getting your specific component:
export default {
components: {
SweetModal: () => import('sweet-modal-vue').then(m => m.SweetModal)
}
}
I recommend you to read this: Async Vue.js Component

Get data from Redux Store after data has been added

I am using a boilerplate called trufflebox's react-auth where
getWeb is called on loading the page (Link to code)
which creates the web3 object (Link to Code)
and stores web3 in the Redux store (Link to code)
Problem: When I retrieve the web3 object from the Redux store, it is undefined, most likely because web3 has not been created yet in Step 2 described above.
What should be the correct way to retrieve web3 from the Redux store only after it has been set?
layouts/test/Test.js
import React, { Component } from 'react';
import store from '../../store';
class Test extends Component {
componentWillMount() {
this.setState({
web3: store.getState().results.payload.web3Instance
})
this.instantiateContract()
}
instantiateContract() {
console.log(this.state.web3) // UNDEFINED!!
}
render() {
return (
<h1>Test</h1>
)
}
}
export default Test
Everything works if I retrieve web3 again without going to the Redux store:
import React, { Component } from 'react';
import getWeb3 from '../../util/web3/getWeb3';
class Test extends Component {
componentWillMount() {
getWeb3
.then(results => {
this.setState({
web3: results.payload.web3Instance
})
this.instantiateContract()
})
}
instantiateContract() {
console.log(this.state.web3)
}
render() {
return (
<h1>Test</h1>
)
}
}
export default Test
Resolve the promise just after creating the store
src/store.js
import getWeb3 from './util/web3/getWeb3';
import { createStore } from 'redux';
//... prepare middlewares and other stuffs , then : create store
const store = createStore(/*....configure it as you want..*/);
// Just after creating store, here the engineering:
getWeb3.then(results => {
// Assuming you have suitable reducer
// Assuming the reducer put the payload in state and accessible via "getState().results.payload.web3Instance"
store.dispatch({ type: 'SAVE_WEB3', payload: results.payload.web3Instance });
});
export default store;
In you ./index.js (where you are rendering the whole app) consider to use Provider component as wrapper to pass store behind the seen and have a singleton store.
src/index.js
import { Provider } from 'react-redux';
import store from './store';
ReactDOM.render(
<Provider store={store}>
<Test />
</Provider>
)
Now, in your component, connect HOC will do everything , see comments below :
src/.../Test.js
import { connect } from 'react-redux';
class Test extends Component {
// No need any lifecyle method , "connect" will do everything :)
render() {
console.log(this.props.web3)
return (
<h1>Test</h1>
)
}
}
// Retrieve from Redux STATE and refresh PROPS of component
function mapStateToProps(state) {
return {
web3: state.results.payload.web3Instance // since you are using "getState().results.payload.web3Instance"
}
}
export default connect(mapStateToProps)(Test); // the awesome "connect" will refresh props
Maybe try calling instantiateContract during the componentWillReceiveProps phase. Check out the following...
componentWillMount() {
this.setState({
web3: store.getState().results.payload.web3Instance
});
}
instantiateContract() {
console.log(this.state.web3); // hopefully not undefined
}
componentWillReceiveProps(nextProps) {
if(nextProps.whatever) {
this.instantiateContract();
}
}
render() {
return (
<h1>Test</h1>
)
}
where nextProps.whatever is what you are mapping from redux (not totally sure what this is given your details). Ideally this is getting fed back into your component and when the value either populates or changes, you then call your function
Also, I see a lot of state management here opposed to what I would expect to see done via props. if componentWillReceiveProps(nextProps) is not a good hook given your application architecture, componentDidUpdate(prevProps, prevState) could be a viable alternative.

Categories

Resources