Categories
discuss

React-Redux – No reducer provided for key “coins”

Not sure why I’m getting the following errors.

I’m just setting up my store, actions and reducers, I haven’t called dispatch on anything yet.

Expected

App runs fine, Redux state is not updated

Results

enter image description here

src/index.js
import React from 'react'
import ReactDOM from 'react-dom'

import { createStore, applyMiddleware, compose } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import reducer from './reducer'

import App from './App'
import css from './coinhover.scss'

const element = document.getElementById('coinhover');

const store = createStore(reducer, compose(
    applyMiddleware(thunk),
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
));

ReactDOM.render(
    <Provider store={ store }>
        <App />
    </Provider>, element);
src/reducer/index.js
import { combineReducers } from 'redux'
import { coins } from './coins'

export default combineReducers({
    coins
});
src/reducer/actions/coins.js
import * as api from '../../services/api'
import { storage, addToPortfolio } from '../../services/coinFactory'

export const ADD_COIN = 'ADD_COIN'

export function getCoin(coin) {
    return dispatch => {
        api.getCoin(coin)
            .then((res_coin)  => addToPortfolio(res_coin))
            .then((portfolio) => dispatch(updatePortfolio(portfolio)));
    }
}

export function updatePortfolio(portfolio) {
    return {
        type: ADD_COIN,
        portfolio
    }
}
finally src/reducer/coins/index.js
import { ADD_COIN } from './actions'

const initialState = [];

export default (state = initialState, action) => {
    switch(action.type) {
        case ADD_COIN:
            return action.portfolio;
        default:
            return state;
    }
}

Answer

Your issue lies with how you’re importing your coins reducer:

import { coins } from './coins'

The latter tries to obtain a named export returned from the file in ./coins.

You are not using any named exports only export default, therefore you just need to import the file as follows:

import coins from './coins';

Using the latter will result with the fact that coins will then contain the value of export default; which will be the coins reducer.

Categories
discuss

Android – How to change menu item icon when clicked

I currently have one item in my menu which is an icon of a pig. What I would like to happen is when I click on the pig, the icon will then change to another image like a chicken. I’ve read other forums on StackOverFlow but still no luck.

I know you cannot use findViewbyId to reference a menu Item but the findItem method is not working for me or at least it says invalid. Please advise.

Here is my current code:

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item android:id="@+id/menuImage"
        android:title=""
        android:icon="@drawable/pig"
        android:orderInCategory="1"
        app:showAsAction="always|withText"/>
    </menu>


    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.menuImage:
            Toast.makeText(this, "YOU THINK YOU GOT THIS?", Toast.LENGTH_SHORT).show();
            MenuItem changeImage = (MenuItem) findViewById(R.id.menuImage);
            changeImage.setIcon(R.drawable.chicken);
            return true;
    }
    return true;
}

Answer

onOptionsItemSelected is called whenever an item in your options menu is selected. The item parameter contains the menu item that was selected.

So you can do this:

item.setIcon(R.drawable.chicken);
Categories
discuss

Convert indefinitely running Runnable from java to kotlin

I have some code like this in java that monitors a certain file:

private Handler mHandler = new Handler();
private final Runnable monitor = new Runnable() {

    public void run() {
        // Do my stuff
        mHandler.postDelayed(monitor, 1000); // 1 second
    }
};

This is my kotlin code:

private val mHandler = Handler()
val monitor: Runnable = Runnable {
    // do my stuff
    mHandler.postDelayed(whatToDoHere, 1000) // 1 second
}

I dont understand what Runnable I should pass into mHandler.postDelayed. What is the right solution? Another interesting thing is that the kotlin to java convertor freezes when I feed this code.

Answer

Lambda-expressions do not have this, but object expressions (anonymous classes) do.

object : Runnable {
    override fun run() {
        handler.postDelayed(this, 1000)
    }
}
Categories
discuss

Conditional Javascript Filter

I have a object containing the following:

assets = [
  { id: 1, type: 'image', url: 'image.jpg' },
  { id: 2, type: 'video', url: 'video.mp4' },
]

I’d like to filter based on user selection of IMAGE, VIDEO, or ALL.

I cannot think of a clean way to filter use for the ALL case.

currentOption = 'image'
assets.filter(asset => asset.type === currentOption)

This will work for IMAGE or VIDEO, but not ALL.

I could check in my filter function:

const currentOption = 'all'
const filterFunc = asset => {
  if (currentOption == 'all') return true
  return asset.type === currentOption
}
assets.filter(filterFunc)

But wouldn’t it be better to short-circuit the filter to not iterate each item?

Edit: To answer questions why not skip filter all together. I was trying to keep it framework agnostic. But this is rendered using react. So I would have to do something like:

<div>
{currentOption === 'all' ?
  assets.map(asset => 
   <img src={asset.url} />
  )
  :
  assets.filter(asset => asset.type === currentOption).map(asset =>
   <img src={asset.url} />
  )
}
</div>

Plus this doesn’t even account for the code to display a video. Basically I was trying to reduce duplication in the view code.

Answer

You could use the ternary operator to decide whether or not to apply the filter:

currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption)

The mapping to images, that you added to the end of your question, could be written like this:

(currentOption === 'all' ? assets : assets.filter(asset => asset.type === currentOption))
    .map( asset => <img src={asset.url} /> )
Categories
discuss

Getting ArtifactId and Version in Spring Boot Starter

I am currently developing a Spring Boot Starter which will host a Restful web service with some meta-data about the running application.

I am having difficulties extracting my artifactId and versionId from my mainfest file. I believe my issue is that the autoconfiguration classes are being loaded before the main Test application so the manifest is not yet available to be discovered. I am not sure if my logic here is correct of if I am approaching the problem from the wrong angle.

I originally followed the following tutorial for setup.

This gave me 3 separate projects

Generic Spring Services with no context AutoConfiguration project for these services Spring Boot starter

I paired the starter with a test project as an end result.

Currently maven is being used with Spring Boot to generate a manifest file.

Implementation-Title: MyExampleProjectWithCustomStarter Implementation-Version: 0.0.1-SNAPSHOT Archiver-Version: Plexus Archiver Built-By: mcf Implementation-Vendor-Id: com.coolCompany Spring-Boot-Version: 1.5.4.RELEASE Implementation-Vendor: Pivotal Software, Inc. Main-Class: org.springframework.boot.loader.JarLauncher Start-Class: com.coolcompany.SpringBootExampleApplication Spring-Boot-Classes: BOOT-INF/classes/ Spring-Boot-Lib: BOOT-INF/lib/ Created-By: Apache Maven 3.5.0 Build-Jdk: 1.8.0_131 Implementation-URL: http://someurl

However, when I attempt to locate the manifest file for the Example project from my generic service package I cannot find the file.

  private String getApplicationVersion(String applicationName, List<Attributes> manifests) {
    String unknownVersion = "0.0.0-UNKNOWN";

    for (Attributes attr : manifests) {
      String title = attr.getValue(IMPL_TITLE);
      String version = attr.getValue(IMPL_VERSION);
      if (version != null) {
        if (applicationName.equalsIgnoreCase(title)) {
          return title + ' ' + version;
        }
      }
    }
    log.warn(
        "Could not find MANIFEST file with '" + applicationName + "' as Implementation-Title."
        + " Meta-API will return buildVersion '" + unknownVersion + "'.");

    return applicationName + ' ' + unknownVersion;
  }

  private List<Attributes> loadManifestFiles() {
    List<Attributes> manifests = new ArrayList<>();
    try {
      Enumeration<URL> resources =
          Thread.currentThread().getContextClassLoader().getResources("/META-INF/MANIFEST.MF");
      while (resources.hasMoreElements()) {
        URL url = resources.nextElement();
        try (InputStream is = url.openStream()) {
          manifests.add(new Manifest(is).getMainAttributes());
          System.out.println("Manifest size:" + manifests.size());
        } catch (IOException e) {
          log.error("Failed to read manifest from " + url, e);
        }
      }
    } catch (IOException e) {
      log.error("Failed to get manifest resources", e);
    }
    return manifests;
  }

Current manifest Implementation-Titles:

Spring Boot Web Starter Spring Boot Starter Spring Boot Spring Boot AutoConfigure Spring Boot Logging Starter null null jcl-over-slf4j null log4j-over-slf4j null Spring Boot Tomcat Starter Apache Tomcat Apache Tomcat Apache Tomcat hibernate-validator null JBoss Logging 3 ClassMate jackson-databind Jackson-annotations Jackson-core spring-web spring-aop spring-beans spring-context spring-webmvc spring-expression Spring Boot Actuator Starter Spring Boot Actuator null ** MyCustom-spring-boot-starter ** MyGenericSpringService null null null Metrics Core JVM Integration for Metrics null null Jackson datatype: JSR310 ** MyService-spring-boot-autoconfigure slf4j-api spring-core ** Missing MyExampleProjectWithCustomStarter

count of manifest records: 44

Answer

After a lot of effort, I found a surprisingly simple answer. This is how spring-boot-actuator gets the information.

The Spring Boot Maven plugin comes equipped with a build-info goal. As long as this goal is triggered in the main project Spring has a BuildProperties class you can wire in for the information.

            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>build-info</id>
                        <goals>
                            <goal>build-info</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

You can access the properties in your starter like:

@Autowired
BuildProperties buildProperties;

...
buildProperties.getArtifact();
buildProperties.getVersion();

You can even specify additional properties from the plugin. See the plugin documentation for more details: https://docs.spring.io/spring-boot/docs/current/maven-plugin/build-info-mojo.html

Unfortunately I never quite got to fully understand why I could not access the correct manifest, but this should help anyone else trying to solve this problem.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..