Trying to figure working with data in reason. I have this graphql query returning data a logging it. Question is how do I access the data in the following component.
let component = ReasonReact.statelessComponent("Home");
let make = (_) => {
...component,
render: (_self) =>
<View>
<Hello message="Hello from home component" />
<FetchEpisodes>
(
(response) => {
Js.log(response);
/* let episodeItems =
Array.of_list(
List.map(
(response) =>
<Episode
key=response##data##allEpisodes##id
episode=response##data##allEpisodes##episode
/>,
)
); */
<div> <h1> (ReasonReact.stringToElement("Episodes!")) </h1> </div>
/* (ReasonReact.arrayToElement(episodeItems)) */
}
)
</FetchEpisodes>
</View>
};
This is the query response:
coming from JS i keep wanting to log allEpisodes with some like response.data...which doesn't work here, obviously
Gists to components: episode component, home.re component
If i uncomment and run, it produces the following error:
```
FAILED: src/pages/home.mlast
/usr/local/lib/node_modules/bs-platform/bin/bsc.exe -pp "/usr/local/lib/node_modules/bs-platform/bin/refmt3.exe --print binary" -ppx '/usr/local/lib/node_modules/bs-platform/bin/reactjs_jsx_ppx_2.exe' -w -30-40+6+7+27+32..39+44+45+101 -nostdlib -I '/Users/shingdev/code/REASON/with-reason-apollo-master/node_modules/bs-platform/lib/ocaml' -bs-super-errors -no-alias-deps -color always -c -o src/pages/home.mlast -bs-syntax-only -bs-binary-ast -impl /Users/shingdev/code/REASON/with-reason-apollo-master/src/pages/home.re
File "/Users/shingdev/code/REASON/with-reason-apollo-master/src/pages/home.re", line 53, characters 17-18:
Error: 2806: <UNKNOWN SYNTAX ERROR>
We've found a bug for you!
/Users/shingdev/code/REASON/with-reason-apollo-master/src/pages/home.re
There's been an error running Reason's refmt parser on a file.
This was the command:
/usr/local/lib/node_modules/bs-platform/bin/refmt3.exe --print binary '/Users/shingdev/code/REASON/with-reason-apollo-master/src/pages/home.re' > /var/folders/qx/xhwh5zfj7z36_bjh5187svx00000gn/T/ocamlpp530e68
```
I'm not understanding how to process the response object when an array is returned. Thank you.
UPDATE per #glennsl's suggestion:
```
let make = (_) => {
...component,
render: (_self) =>
<View>
<Hello message="Hello from home component" />
/* <Greeting name="Tony" /> */
<FetchEpisodes>
(
(response) => {
let episodeItems =
response##data##allEpisodes
|> Array.map((episode) => <Episode key=episode##id title=episode##title />);
<div> <h1> (ReasonReact.stringToElement("Episodes!")) </h1> </div>(
ReasonReact.arrayToElement(episodeItems)
)
}
)
</FetchEpisodes>
</View>
};
```
This produces the following error:
I'm figuring its coming because the types arent being passed to episode.re
```
let component = ReasonReact.statelessComponent("Episode");
let make = (~style=?, ~episode, _children) => {
...component,
render: (_self) => <View ?style> <h1> (ReasonReact.stringToElement(episode)) </h1> </View>
};
```
Am I supposed to pass list(episode) somewhere?
UPDATE 2: This code works as far as JSX thanks to #glennsl
```
let make = (_) => {
...component,
render: (_self) =>
<View>
<Hello message="Hello from home component" />
/* <Greeting name="Tony" /> */
<FetchEpisodes>
(
(response) => {
let episodeItems =
response##data##allEpisodes
|> Array.map((episode) => <Episode key=episode##id episode=episode##episode />);
<div>
<h1> (ReasonReact.stringToElement("Episodes!")) </h1>
(ReasonReact.arrayToElement(episodeItems))
</div>
}
)
</FetchEpisodes>
</View>
};
```
This should work, I think:
type episode = {. "id": string, "title": string, "episode": string};
type data = {. "allEpisodes": array(episode)};
...
(response) => {
let episodeItems =
response##data##allEpisodes
|> Array.map((episode) =>
<Episode key=episode##id
episode=episode##episode />);
<div>
<h1> (ReasonReact.stringToElement("Episodes!")) </h1>
(ReasonReact.arrayToElement(episodeItems))
</div>
}
Let me know if it doesn't, or if any of this confuses you I'll happily explain.
Edit: You've also typed data##allEpisodes as list(episode) when it's actually array(episode). Updated the code block above. A list is not the same as an array, the former is a linked list type while the latter is equivalent to a JavaScript array.
Edit 2: Fixed JSX
response##data##allEpisodes
|> Array.map((episode) =>
This won't work because response##data##allEpisodes returns undefined. I believe it's because in [reason-apollo]: https://github.com/Gregoirevda/reason-apollo/blob/master/src/ReasonApollo.re#L29 data is typed as a string.
Related
I use react-native-elements library.
in ListItem Accordion there is onPress option to expand and unexpand list items.
but when I press one item, all of items expand!
screen shot 1
here is part of my code:
export class MyList extends Component {
state= {
expanded:false,
};
constructor(props) {
super(props);
this.state = {
expanded:false
};
}
handleToggle=()=>{
const {expanded}=this.state;
if(expanded){
this.setState({expanded:false});
}else{
this.setState({expanded:true})
}
}
render() {
return (
...
<View>
{list.map((l, i) => (
<ListItem.Accordion key={i}
content={
<>
<ListItem.Content>
<ListItem.Title>{l.name}</ListItem.Title>
<Avatar title={l.name[0]} source={{ uri: l.avatar_url }} />
</ListItem.Content>
</>
}
isExpanded={this.state.expanded}
onPress={this.handleToggle}
>
<ListItem key={i} bottomDivider>
<ListItem.Content>
<ListItem.Subtitle>{l.city}</ListItem.Subtitle>
<View style={styles.subtitleView}>
<Image source={require('../Images/4.5_stars.svg.png')} style={styles.ratingImage}/>
<Text style={styles.ratingText}>5 votes</Text>
</View>
</ListItem.Content>
<ListItem.Chevron />
</ListItem>
</ListItem.Accordion>
))}
...
is it my props problem?? if yes, how can I pass the item for each "onPress"??
Surely you already solved your problem.
I had the same problem and I solved it myself since I couldn't find a solution.
It turns out that it was very simple and probably arises from not being used to the React way of working.
A component must be created for your custom <ListItem.Accordion>,
then you get something like
{Turneras ? (Turneras.map((Turnera, i) => (
<ItemAccordion Turnera={Turnera} ></ItemAccordion>
))) : null
}
As easy as that, since each component will have its state expanded and it works perfectly.
I have a component that switch Language of a nuxtjs application using nuxt-i18n as follows
<template>
<div class="navbar-item has-dropdown is-hoverable">
<a class="navbar-link langpicker">{{ $t("language_picker") }} </a>
<div class="navbar-dropdown is-hidden-mobile">
<div>
<nuxt-link
v-if="currentLanguage != 'en'"
class="navbar-item"
:to="switchLocalePath('en')"
>
<img src="~/static/flags/us.svg" class="flagIcon" /> English
</nuxt-link>
<nuxt-link
v-if="currentLanguage != 'el'"
class="navbar-item"
:to="switchLocalePath('el')"
>
<img src="~/static/flags/el.svg" class="flagIcon" /> Ελληνικά
</nuxt-link>
</div>
</div>
</div>
</template>
<script>
export default {
name: "LangPicker",
computed: {
currentLanguage() {
return this.$i18n.locale || "en";
}
}
};
</script>
I want to write a Unit Test that test the correct language switch on 'nuxt-link' click.
So far I have the following
import { mount, RouterLinkStub } from "#vue/test-utils";
import LangPicker from "#/components/layout/LangPicker";
describe("LangPicker with locale en", () => {
let cmp;
beforeEach(() => {
cmp = mount(LangPicker, {
mocks: {
$t: msg => msg,
$i18n: { locale: "en" },
switchLocalePath: msg => msg
},
stubs: {
NuxtLink: RouterLinkStub
}
});
});
it("Trigger language", () => {
const el = cmp.findAll(".navbar-item")
});
});
cmp.find(".navbar-item") return an empty object.
I don't know how I must set up to "trigger" the click event.
const el = cmp.findAll(".navbar-item")[1].trigger("click");
make sure your find selector is correct.
const comp = cmp.find(".navbar-item");
comp.trigger('click');
you can use chrome dev tools selector utility.
Refer this link for detailed information.
I am trying out Reason-React. I am facing a problem when I try to add a key to one of the components.
I have a TodoApp that takes a list of TodoItem as state. The app works fine when I don't have a key for the TodoItem. When I add it, however I am getting a compilation error. I am adding the files here for reference:
TodoItem.re:
type item = {
id: int,
title: string,
completed: bool
};
let lastId = ref(0);
let newItem = () => {
lastId := lastId^ + 1;
{id: lastId^, title: "Click a button", completed: false}
};
let toString = ReasonReact.stringToElement;
let component = ReasonReact.statelessComponent("TodoItem");
let make = (~item, children) => {
...component,
render: (self) =>
<div className="item">
<input _type="checkbox" checked=(Js.Boolean.to_js_boolean(item.completed)) />
(toString(item.title))
</div>
};
TodoApp.re:
let toString = ReasonReact.stringToElement;
type state = {items: list(TodoItem.item)};
type action =
| AddItem;
let component = ReasonReact.reducerComponent("TodoApp");
let currentItems = [TodoItem.{id: 0, title: "ToDo", completed: false}];
let make = (children) => {
...component,
initialState: () => {items: currentItems},
reducer: (action, {items}) =>
switch action {
| AddItem => ReasonReact.Update({items: [TodoItem.newItem(), ...items]})
},
render: ({state: {items}, reduce}) => {
let numOfItems = List.length(items);
<div className="app">
<div className="title">
(toString("What to do"))
<button onClick=(reduce((_evt) => AddItem))> (toString("Add Something")) </button>
</div>
<div className="items">
(
ReasonReact.arrayToElement(
Array.of_list(
(List.map((item) => <TodoItem key=(string_of_int(item.id)) item />, items))
/*List.map((item) => <TodoItem item />, items) This works but the above line of code with the key does not*/
)
)
)
</div>
<div className="footer"> (toString(string_of_int(numOfItems) ++ " items")) </div>
</div>
}
};
I've added a comment near the line where the error occurs.
The error reads as Unbound record field id, but I am not able to figure out how it is not bound. What am I missing here?
Type inference is unfortunately a bit limited when it comes to inferring the type of a record from another module based on the usage of record fields, so you need to give it some help. Two options that should work are:
Annotating the type of ìtem:
List.map((item: TodoItem.item) => <TodoItem key=(string_of_int(item.id)) item />)
or locally opening the module where the record field is used:
List.map((item) => <TodoItem key=(string_of_int(item.TodoItem.id)) item />)
Hello I am trying to simulate an 'ended' event on and HTML5 audio element without success. Here is my component:
export class AudioPlayer extends Component {
constructor (props) {
super(props);
// Auto play turned off when component render for the first time
this.autoPlay = false;
this.shouldAudioAutoPlay = this.shouldAudioAutoPlay.bind(this);
}
componentDidMount () {
let audio = findDOMNode(this.player);
if (audio) {
console.log('in')
audio.addEventListener('ended', () => {
console.log('event dispatched')
this.props.audioFinished();
});
}
}
render () {
return (
<Media>
<div>
<div className="media-player">
<Player src={this.props.audioUrl.url}
autoPlay={false}
id="activeModuleAudio"
vendor="audio"
ref={(player) => { this.player = player }}
/>
</div>
<div className="ap-main">
<div className="ap-controls">
<PlayButton />
<ProgressBar enableUserInput={this.props.enableUserInput} audio={this.props.audioUrl} />
</div>
<a href={this.props.facebookUrl}><div className="ap-facebook-group" /></a>
</div>
</div>
</Media>
);
}
}
And here the test:
it('should dispatch an action when audio is finished', () => {
let mockedAudioFinishedAction = jest.fn();
let mockedEnableUserInputAction = jest.fn();
let mountedWrapper = mount(
<AudioPlayer
audioUrl={{ url: 'audio-url', autoPlay: true }}
facebookUrl="facebook-url" audioFinished={mockedAudioFinishedAction}
enableUserInput={mockedEnableUserInputAction}
/>
);
mountedWrapper.update();
mountedWrapper.update();
mountedWrapper.find(Player).simulate('ended');
expect(mockedAudioFinishedAction.mock.calls.length).toBe(1);
});
The simulate seems to not be dispatching the event,despite working on the browser. Any thoughts?
Thanks in advance!
I am working on an app which was created with the Vue loader's webpack template.
I included testing with Karma as an option when creating the project, so it was all set up and I haven't changed any of the config.
The app is a Github user lookup which currently consists of three components; App.vue, Stats.vue and UserForm.vue. The stats and form components are children of the containing app component.
Here is App.vue:
<template>
<div id="app">
<user-form
v-model="inputValue"
#go="submit"
:input-value="inputValue"
></user-form>
<stats
:username="username"
:avatar="avatar"
:fave-lang="faveLang"
:followers="followers"
></stats>
</div>
</template>
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import _ from 'lodash'
import UserForm from './components/UserForm'
import Stats from './components/Stats'
Vue.use(VueAxios, axios)
export default {
name: 'app',
components: {
UserForm,
Stats
},
data () {
return {
inputValue: '',
username: '',
avatar: '',
followers: [],
faveLang: '',
urlBase: 'https://api.github.com/users'
}
},
methods: {
submit () {
if (this.inputValue) {
const api = `${this.urlBase}/${this.inputValue}`
this.fetchUser(api)
}
},
fetchUser (api) {
Vue.axios.get(api).then((response) => {
const { data } = response
this.inputValue = ''
this.username = data.login
this.avatar = data.avatar_url
this.fetchFollowers()
this.fetchFaveLang()
}).catch(error => {
console.warn('ERROR:', error)
})
},
fetchFollowers () {
Vue.axios.get(`${this.urlBase}/${this.username}/followers`).then(followersResponse => {
this.followers = followersResponse.data.map(follower => {
return follower.login
})
})
},
fetchFaveLang () {
Vue.axios.get(`${this.urlBase}/${this.username}/repos`).then(reposResponse => {
const langs = reposResponse.data.map(repo => {
return repo.language
})
// Get most commonly occurring string from array
const faveLang = _.chain(langs).countBy().toPairs().maxBy(_.last).head().value()
if (faveLang !== 'null') {
this.faveLang = faveLang
} else {
this.faveLang = ''
}
})
}
}
}
</script>
<style lang="stylus">
body
background-color goldenrod
</style>
Here is Stats.vue:
<template>
<div class="container">
<h1 class="username" v-if="username">{{username}}</h1>
<img v-if="avatar" :src="avatar" class="avatar">
<h2 v-if="faveLang">Favourite Language: {{faveLang}}</h2>
<h3 v-if="followers.length > 0">Followers ({{followers.length}}):</h3>
<ul v-if="followers.length > 0">
<li v-for="follower in followers">
{{follower}}
</li>
</ul>
</div>
</template>
<script>
export default {
name: 'stats',
props: [
'username',
'avatar',
'faveLang',
'followers'
]
}
</script>
<style lang="stylus" scoped>
h1
font-size 44px
.avatar
height 200px
width 200px
border-radius 10%
.container
display flex
align-items center
flex-flow column
font-family Comic Sans MS
</style>
And here is UserForm.vue:
<template>
<form #submit.prevent="handleSubmit">
<input
class="input"
:value="inputValue"
#input="updateValue($event.target.value)"
type="text"
placeholder="Enter a GitHub username..."
>
<button class="button">Go!</button>
</form>
</template>
<script>
export default {
props: ['inputValue'],
name: 'user-form',
methods: {
updateValue (value) {
this.$emit('input', value)
},
handleSubmit () {
this.$emit('go')
}
}
}
</script>
<style lang="stylus" scoped>
input
width 320px
input,
button
font-size 25px
form
display flex
justify-content center
</style>
I wrote a trivial test for UserForm.vue which test's the outerHTML of the <button>:
import Vue from 'vue'
import UserForm from 'src/components/UserForm'
describe('UserForm.vue', () => {
it('should have a data-attribute in the button outerHTML', () => {
const vm = new Vue({
el: document.createElement('div'),
render: (h) => h(UserForm)
})
expect(vm.$el.querySelector('.button').outerHTML)
.to.include('data-v')
})
})
This works fine; the output when running npm run unit is:
UserForm.vue
✓ should have a data-attribute in the button outerHTML
However, when I tried to write a similarly simple test for Stats.vue based on the documentation, I ran into a problem.
Here is the test:
import Vue from 'vue'
import Stats from 'src/components/Stats'
// Inspect the generated HTML after a state update
it('updates the rendered message when vm.message updates', done => {
const vm = new Vue(Stats).$mount()
vm.username = 'foo'
// wait a "tick" after state change before asserting DOM updates
Vue.nextTick(() => {
expect(vm.$el.querySelector('.username').textContent).toBe('foo')
done()
})
})
and here is the respective error when running npm run unit:
ERROR LOG: '[Vue warn]: Error when rendering root instance: '
✗ updates the rendered message when vm.message updates
undefined is not an object (evaluating '_vm.followers.length')
I have tried the following in an attempt to get the test working:
Change how the vm is created in the Stats test to be the same as the UserForm test - same error is returned
Test individual parts of the component, for example the textContent of a div in the component - same error is returned
Why is the error referring to _vm.followers.length? What is _vm with an underscore in front? How can I get around this issue to be able to successfully test my component?
(Repo with all code: https://github.com/alanbuchanan/vue-github-lookup-2)
Why is the error referring to _vm.followers.length? What is _vm with an underscore in front?
This piece of code is from the render function that Vue compiled your template into. _vm is a placeholder that gets inserted automatically into all Javascript expressions when vue-loader converts the template into a render function during build - it does that to provide access to the component.
When you do this in your template:
{{followers.length}}
The compiled result in the render function for this piece of code will be:
_vm.followers.length
Now, why does the error happen in the first place? Because you have defined a prop followers on your component, but don't provide any data for it - therefore, the prop's value is undefined
Solution: either you provide a default value for the prop:
// Stats.vue
props: {
followers: { default: () => [] }, // function required to return fresh object
// ... other props
}
Or you propvide acual values for the prop:
// in the test:
const vm = new Vue({
...Stats,
propsData: {
followers: [/* ... actual data*/]
}
}).$mount()